我有一个声明如下的表
declare @t table(ProductCode char(25), Description char(100), Supplier char(50), ForwardOrder bit, SalesNotDelivered decimal(15,2))
使用虚拟数据
insert into @t(ProductCode, Description, Supplier, ForwardOrder, SalesNotDelivered)
values ('ABC', 'DescABC', 'S1', 1, 10)
insert into @t(ProductCode, Description, Supplier, ForwardOrder, SalesNotDelivered)
values ('ABC', 'DescABC', 'S1', 0, 20)
insert into @t(ProductCode, Description, Supplier, ForwardOrder, SalesNotDelivered)
values ('ABC', 'DescABC', 'S1', 0, 30)
insert into @t(ProductCode, Description, Supplier, ForwardOrder, SalesNotDelivered)
values ('ABC', 'DescABC', 'S1', 0, 40)
insert into @t(ProductCode, Description, Supplier, ForwardOrder, SalesNotDelivered)
values ('ABC', 'DescABC', 'S1', 0, 50)
insert into @t(ProductCode, Description, Supplier, ForwardOrder, SalesNotDelivered)
values ('DEF', 'DescDEF', 'S2', 0, 500)
我想对SalesNotDelivered列求和,但在结果集中将其拆分为两列 - 一列显示转发订单总和,另一列显示非正向订单总和
因此,使用上面的数据,我最终得到: -
ProductCode Description Supplier SalesNotDelivered SalesNotDeliveredFwdOrders
ABC DescABC S1 140 10
DEF DescDEF S2 500 0
执行此操作的最有效查询是什么?
答案 0 :(得分:2)
SELECT ProductCode, [Description], Supplier,
ISNULL(SUM(CASE WHEN ForwardOrder <> 1 THEN SalesNotDelivered END), 0) AS SalesNotDelivered,
ISNULL(SUM(CASE WHEN ForwardOrder = 1 THEN SalesNotDelivered END), 0) AS SalesNotDeliveredFwdOrders
FROM @t
GROUP BY ProductCode, [Description], Supplier
SQLFiddle
上的演示
答案 1 :(得分:0)
在SQL中它有点像
SELECT
ProductCode, Description,Supplier,
SUM(SalesNotDelivered) as SalesNotDelivered,
SUM(ForwardOrder)as SalesNotDeliveredFwdOrders
FROM t
GROUP BY
Supplier