已知 ,数据库两个字段,年,月。现在要按照季度分组查询,怎么写sql语句?

已知 ,数据库两个字段,年,月。现在要按照季度分组查询,怎么写sql语句?,第1张

先case when将月份变成季度然后再group by即可,SQL如下:

select year, quarter, count(1)

from (

    select year,

        case

        when month <4 then 1

        when month <7 then 2

        when month <10 then 3

        else 4

        end as quarter

    from table

) as result

group by year, quarter

select Year as 年份

, 第一季度= sum(case Q when 0 then amount end)

, 第二季度= sum(case Q when 1 then amount end)

, 第三季度= sum(case Q when 2 then amount end)

, 第四季度= sum(case Q when 3 then amount end)

from (

select year(ShippedDate) as Y, month(ShippedDate) / 4 as Q,

UnitPrice*Quantity*(1-Discount) as amount

from Orders,[Order Details]

where Orders.OrderID=[Order Details].OrderID

and year(ShippedDate) is not null

group by year(ShippedDate) , month(ShippedDate) / 4

) as a

group by Y

order by Y


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/sjk/6766294.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-03-28
下一篇 2023-03-28

发表评论

登录后才能评论

评论列表(0条)

保存