预先感谢您的帮助。我期待成为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;
答案 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_Sales
(order by
)。