Microsoft SQL Server中年份和季度的汇总功能

时间:2018-10-23 13:23:27

标签: sql sql-server

预先感谢您的帮助。我期待成为Stack Overflow社区的一员:)

我只是想学习Microsoft SQL Server的SQL。

我想使用聚合函数,并从数据类型为DateTime的列中按年份和季度分组。

我可以按如下所示按季度完成,也可以按年份进行,但不能一起完成。

select sum(subtotal) As Total_Sales, datepart(quarter, OrderDate) as Total_Quarter

from sales.SalesOrderHeader

group by datepart(quarter, OrderDate)

order by sum(subtotal) desc;  

1 个答案:

答案 0 :(得分:2)

datepart(year, OrderDate)子句中也使用group by

select sum(subtotal) as Total_Sales, 
       datepart(year, OrderDate) as yr,
       datepart(quarter, OrderDate) as Total_Quarter
from sales.SalesOrderHeader
group by datepart(quarter, OrderDate), datepart(year, OrderDate)
order by Total_Sales desc;  

您可以在alias子句中使用列Total_Salesorder by)。