将SQL查询结果拆分为其他列

时间:2013-11-16 09:55:42

标签: sql tsql

我有一个声明如下的表

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

执行此操作的最有效查询是什么?

2 个答案:

答案 0 :(得分:2)

听起来你需要一个带有CASE子句的GROUP BY表达式

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