2010-07-08 43 views
1

我希望我解釋得很好。我與此查詢掙扎:許多行到一行結果

我有這個表是這樣的:

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 
+0

也許如果您向我們展示了表格結構,我們可以看到更多 - 因爲它看起來我看不出問題是什麼。 – Ragster 2010-07-08 16:29:56

回答

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 

案例陳述返回null默認情況下,sum忽略空值。

3

你可以像@Andomar所顯示的那樣用group by和sum tricks(max works)來做到這一點。

或者,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;