产生许多行到一行

时间:2010-07-08 16:24:03

标签: sql sql-server-2005 tsql

我希望我能很好地解释这一点。我正在努力解决这个问题:

我有这样的表:

InvoiceNum
Amount
Type  - where type could be item, shipping or tax. 

所以我要返回的是每张发票一行:InvoiceNum,ItemAmount,ShippingAmount,TaxAmount。

以下是一个例子:

Invoicenum Amount Type
1          $32    Item
1          $2     Shipping
1          $1     Tax 

我想要回复:

InvoiceNum ItemAmount ShippingAmount TaxAmount 
1          $32        $2             $1

2 个答案:

答案 0 :(得分:4)

您可以使用group by汇总行,并且可以使用case选择特定行:

select  InvoiceNum
,       sum(case when Type = 'Item' then Amount end) as ItemAmount
,       sum(case when Type = 'Shipping' then Amount end) as ShippingAmount
,       sum(case when Type = 'Tax' then Amount end) as TaxAmount
from    YourTable
group by
        InvoiceNum

case语句默认返回nullsum忽略空值。

答案 1 :(得分:3)

您可以使用分组依据和总和技巧(最大值也可以)执行此操作,如@Andomar所示。

或者,Microsoft SQL Server支持PIVOT操作的语法,这有助于此类查询。您仍然需要对列名进行硬编码。

SELECT InvoiceNum, [Item] AS ItemAmount, [Shipping] AS ShippingAmount, [Tax] AS TaxAmount
FROM 
(SELECT InvoiceNum, Amount, Type FROM InvoiceTable ) i
PIVOT
(
  MAX(Amount)
  FOR Type IN ([Item], [Shipping], [Tax])
) AS pvt;