首页 > 解决方案 > 如何在 SQL 中按季度(1 年 = 4 个季度)分组?

问题描述

问题描述:显示每个客户和产品组合的 4 个季度的平均销售量,Q1、Q2、Q3 和 Q4(在四个单独的列中)-Q1 是一年的前 3 个月(1 月、2 月和 3 月), Q2 接下来的 3 个月(4 月、5 月和 6 月),依此类推——忽略日期的 YEAR 部分(即,2001 年 3 月 11 日被视为与 2002 年 3 月 11 日等相同的日期)。还计算“整个”年的平均值(再次忽略 YEAR 组件,意味着简单地计算 AVG)以及总量(SUM)和计数(COUNT)。

表格如下在此处输入图像描述

示例结果在此处输入图像描述

我是 SQL 的初学者,遇到了这样的问题。它只需要使用聚合函数和 group by 子句对 4 个季度进行分组。

标签: sqlpostgresql

解决方案


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_full) 用于计算结果表中的最后 3 列。最终选择将按季度分别计算的平均值加入结果。相信初学者不容易理解,欢迎提问。


推荐阅读