如何在SQL中按季度(1年=4个季度)分组?
问题描述:显示每个客户和产品组合的四个季度(第一季度、第二季度、第三季度和第四季度)的平均销售数量,分为四列——第一季度为一年的前三个月(1月、2月和3月),第二季度为下三个月(4月、5月和6月),以此类推——忽略日期的年组成部分,即:。,2001年11月3日被视为与2002年11月3日等相同的日期。也可以忽略年份成分,再次计算“整个”年份的平均值,这意味着只需计算平均值以及总数量总和和计数 下表: 样本结果: 我是SQL的初学者,遇到了这样的问题。它只需要使用聚合函数和GROUPBY子句对4个季度进行分组如何在SQL中按季度(1年=4个季度)分组?,sql,postgresql,Sql,Postgresql,问题描述:显示每个客户和产品组合的四个季度(第一季度、第二季度、第三季度和第四季度)的平均销售数量,分为四列——第一季度为一年的前三个月(1月、2月和3月),第二季度为下三个月(4月、5月和6月),以此类推——忽略日期的年组成部分,即:。,2001年11月3日被视为与2002年11月3日等相同的日期。也可以忽略年份成分,再次计算“整个”年份的平均值,这意味着只需计算平均值以及总数量总和和计数 下表: 样本结果: 我是SQL的初学者,遇到了这样的问题。它只需要使用聚合函数和GROUPBY子句对4个
with cte as (
select
customer,
product,
case
when (month < 4) then 'Q1'
when (month >= 4 AND month < 7) then 'Q2'
when (month >= 7 AND month < 10) then 'Q3'
when (month >= 10) then 'Q4'
end AS quarter,
quant
from bgg.table_sof
),
cte_full as (
select
customer,
product,
avg(quant) as average,
sum(quant) as total,
count(quant) as count
from bgg.table_sof
GROUP BY customer, product
)
select
cte_full.customer,
cte_full.product,
avg(cte1.quant) as Q1_AVG,
avg(cte2.quant) as Q2_AVG,
avg(cte3.quant) as Q3_AVG,
avg(cte4.quant) as Q4_AVG,
average,
total,
count
from cte_full
left join cte cte1 on cte_full.customer = cte1.customer and cte_full.product = cte1.product
left join cte cte2 on cte_full.customer = cte2.customer and cte_full.product = cte2.product
left join cte cte3 on cte_full.customer = cte3.customer and cte_full.product = cte3.product
left join cte cte4 on cte_full.customer = cte4.customer and cte_full.product = cte4.product
where cte1.quarter = 'Q1' OR cte2.quarter = 'Q2' OR cte3.quarter = 'Q3' OR cte4.quarter = 'Q4'
group by cte_full.customer, cte_full.product, average, total, count;
对于初学者来说,这是一项棘手的任务。我的建议是从一些理论和简单的实践开始
有两个CTE通用表表达式:
第一个是从月份开始定义季度。
第二个cte_已满,用于计算结果表中的最后3列。
最终选择按季度分别计算得出的平均值。
我相信这对初学者来说并不容易理解,请随意提问。最好将示例数据呈现为。有关如何创建美观的表的一些提示,请参阅。组合:您必须加入表。平均值:使用聚合函数和GROUP BY子句。请阅读。@Laurenz Albe感谢您的回答。为了获得四个季度的平均值,我应该按哪个属性分组?你能再详细解释一下吗?Thanks@CL对不起,我不需要答案或密码。谢谢你的回答,我想这很清楚。但如果我只想使用聚合函数和一些基本语法,那就意味着我不需要使用“CASE”语法。那我怎么才能得到答案呢。