2012-04-06 72 views
1

我在查詢時遇到了一些問題。我試圖確定「類別」字段是A,B還是C,然後根據類別創建字段。該領域將總結支付領域。但我遇到了錯誤,說「附近的關鍵字爲不正確的語法」。我在SQL視圖中創建這個。使用SQL Server 2008嘗試根據案例聲明創建字段

SELECT r.id, r.category 
CASE 
WHEN r.category = 'A' then SUM(r.payment) As A_payments 
WHEN r.category = 'B' then SUM(r.payment) As B_payments 
WHEN r.category = 'C' then SUM(r.payment) As C_payments 
END 
FROM r_invoiceTable As r 
GROUP BY r.id, r.category 

我在那裏,因爲我有數據有A,B和C

樣品數據 - r_invoiceTable

Id --- Category ---- Payment 
222  A  ---- 50 
444  A  ---- 30 
111  B  ---- 90 
777  C  ---- 20 
555  C  ---- 40 

所有上述情況下應該執行數據期望的輸出 A_payments = 80,B_payments = 90,C_payments = 60

+0

是的,但我想要有3個獨立的領域......我不能只有一個領域。我需要使用基於類別的付款總和創建3個單獨的字段。對於你計算相同'SUM'的每個類別,都要使用 – dido 2012-04-06 16:38:28

+0

;使用'CASE'有什麼意義? – mshsayem 2012-04-06 16:42:36

+0

@mshsayem每個類別都會有不同的總和。這就是爲什麼我需要按類別分開 – dido 2012-04-06 16:50:11

回答

4

也許你正在尋找這樣的:

SELECT 
    SUM(CASE WHEN category = 'A' THEN payment END) AS A_payments, 
    SUM(CASE WHEN category = 'B' THEN payment END) AS B_payments, 
    SUM(CASE WHEN category = 'C' THEN payment END) AS C_payments 
FROM r_invoiceTable 
+0

是的,這是我需要的,謝謝! – dido 2012-04-06 17:43:00

1

可能是你想要的(類別明智的支付金額)?:

SELECT r.category, SUM(r.payment) As Payments 
FROM r_invoiceTable As r 
GROUP BY r.category 

輸出將是這樣的:

category  Payments 
--------- ------------ 
    A   80 
    B   90 
    C   60 

如果你喜歡在一個排在這裏,這些數字是一個天真的做法:

SELECT 
    (SELECT SUM(r.payment) From r_invoiceTable As r Where r.category = 'A') as A_Payment, 
    (SELECT SUM(r.payment) From r_invoiceTable As r Where r.category = 'B') as B_Payment, 
    (SELECT SUM(r.payment) From r_invoiceTable As r Where r.category = 'C') as C_Payment 
+0

那麼,上述解決方案將提供3個獨立的列嗎?因爲在我的Web應用程序中,我必須放置3個獨立的列。 – dido 2012-04-06 17:16:18

1
SELECT * 
FROM dbo.r_invoiceTable 
PIVOT 
(SUM(payment) 
FOR category IN ([a],[b],[c]) 
) AS pivoted 
+1

您必須將源中的列限制爲「payment」和「category」。否則'id'和其他列(如果有的話)也會參與分組。即代替'FROM dbo.r_invoiceTable',您需要選擇'FROM(SELECT payment,category FROM dbo.r_invoiceTable)alias'。 – 2012-04-06 17:29:25