我有如下表:SQL查询组
SalesDate smalldatetime,
ProductId varchar(20),
QuantitySold tinyint,
Price smallmoney
我想最后1M,3M,1Y每个产品销售的总量。我如何在一个查询中做到这一点?到目前为止,我的尝试是运行三个单独的查询,每个时间段一个,然后使用UNION组合它们。有没有更好的办法?我使用MS SQL 2008
我有如下表:SQL查询组
SalesDate smalldatetime,
ProductId varchar(20),
QuantitySold tinyint,
Price smallmoney
我想最后1M,3M,1Y每个产品销售的总量。我如何在一个查询中做到这一点?到目前为止,我的尝试是运行三个单独的查询,每个时间段一个,然后使用UNION组合它们。有没有更好的办法?我使用MS SQL 2008
您可以更轻松地与多个列做到这一点:
select productId,
sum(case when salesdate >= dateadd(month, -1, getdate()) then quantitysold else 0 end) as qs1m,
sum(case when salesdate >= dateadd(month, -3, getdate()) then quantitysold else 0 end) as qs3m
sum(case when salesdate >= dateadd(month, -12, getdate()) then quantitysold else 0 end) as qs12m
from table t
group by productId;
(注:你可能想至少从getdate()
删除次,但你可能有一个完全不同的获取“原始”日期的方法。)
由于时间段重叠,因此与列(和条件聚合)相比,对于每个时间段而言,使用单独的行更容易。
不,如果你想让它们垂直叠放,那么UNION是最好的选择。 – 2014-09-24 15:05:38