2010-12-22 65 views
1

是否有可能根據不同的where子句計算多個總量?例如:是否可以聚合不同的where子句?

比方說,我有兩個表,一個用於發票,一個用於InvoiceLineItems。發票表中有一個發票總計字段,並且InvoiceLineItems表中的每個發票行項目記錄都包含一個字段,該字段表示該行項目是否可以折扣。我需要三個總和,其中一個折扣= 0,一個折扣= 1,折扣無關。這樣,我的輸出將是:

InvoiceNumber Total DiscountableTotal NonDiscountableTotal 
------------- ----- ----------------- -------------------- 
1    53.27 27.27    16.00 
2    38.94 4.76    34.18 
3... 

我到目前爲止發現的唯一方法是使用類似:

Select i.InvoiceNumber, 
     i.Total, 
     t0.Total As DiscountableTotal, 
     t1.Total As NonDiscountableTotal 
From Invoices i 
    Left Join (
     Select InvoiceNumber, 
       Sum(Amount), 
     From  InvoiceLineItems 
     Where Discountable = 0 
     Group By InvoiceNumber 
    ) As t0 On i.InvoiceNumber = t0.InvoiceNumber 
    Left Join (
     Select InvoiceNumber, 
       Sum(Amount) 
     From  InvoiceLineItems 
     Where Discountable = 1 
     Group By InvoiceNumber 
    ) As t1 On i.InvoiceNumber = t1.InvoiceNumber 

這似乎有些繁瑣,這將是很好,如果我能做些什麼像:

Select InvoiceNumber, 
     Sum(Amount) Where Discountable = 1 As Discountable 
     Sum(Amount) Where Discountable = 0 As NonDiscountable 
Group By InvoiceNumber 

我知道SQL是完全無效的,但它在邏輯上描繪什麼,我試圖做...

TIA

P.S.我需要這個在SQL Server 2000實例上運行,但是如果/我如何在SQL Server 2005/2008上實現這一點,我也感興趣(以備將來參考)。

回答

7

用途:

SELECT i.invoicenumber, 
     SUM(CASE WHEN i.discountable = 1 THEN i.amount ELSE 0 END) AS discountable, 
     SUM(CASE WHEN i.discountable = 0 THEN i.amount ELSE 0 END) AS NonDiscountable 
    FROM INVOICES i 
GROUP BY i.invoicenumber 

要獲得發票表中的任何其他列(IE:總),你必須做一個自我聯接:

SELECT x.invoicenumber, 
     x.total, 
     y.discountable, 
     y.nondiscountable 
    FROM INVOICES x 
    JOIN (SELECT i.invoicenumber, 
       SUM(CASE WHEN i.discountable = 1 THEN i.amount ELSE 0 END) AS discountable, 
       SUM(CASE WHEN i.discountable = 0 THEN i.amount ELSE 0 END) AS NonDiscountable 
      FROM INVOICES i 
     GROUP BY i.invoicenumber) y ON y.invoicenumber = x.invoicenumber 
+1

我不知道爲什麼我從來沒有想到這一點...似乎很明顯,現在它在我面前。謝謝。 – BenAlabaster 2010-12-22 18:54:19

+0

+1代表第一個代碼段。不直觀,但它工作得很好。 – 2010-12-22 20:47:07

-1

不能確定實際語法,但這樣的事情應該工作:

Select InvoiceNumber, 
     Sum(IF(Discountable=1;Amount;0)) As IsDiscountable 
     Sum(IF(Discountable=0;Amount;0)) As NonDiscountable 
From Invoice 
Group By InvoiceNumber 
相關問題