SQL Server 2008:如何根据两个条件求和



如果我在杂货店工作,需要为库存下订单,我们一个月会下多次订单,而不是一个大订单。

5[/tr>
项目 ETA QTY
Apples 21年5月6日 10
苹果 6/12/21
苹果 6/30/21香蕉
香蕉
谷物 21年5月15日 10
谷物 谷物

您只需使用条件聚合:

select item,
sum(case when month(eta) = 5 then qty else 0 end) as may,
sum(case when month(eta) = 6 then qty else 0 end) as jun,
sum(case when month(eta) = 7 then qty else 0 end) as jul
from inventory i
group by item;

我要提醒你,使用几个月而不使用一年可能会导致问题。使用不受支持的软件也是如此--不再支持SQL Server 2008。

首先应该按项目和月份对数据进行分组,然后使用pivot将行转换为列。

select
item, 
isnull(may,0) as May, 
isnull(june,0) as June, 
isnull(july,0) as July
from
(
select item, datename(month, ETA) as _month, sum(qty) as qty
from Inventory
group by item, datename(month, ETA)
) d
pivot
(
sum(qty)
for _month in (may, june, july)
) piv;

最新更新