尝试根据案例陈述创建字段

时间:2012-04-06 16:32:27

标签: sql sql-server sql-server-2008 join aggregate-functions

我在查询下面遇到一些问题。我试图确定“类别”字段是A,B还是C,然后根据类别创建字段。该字段将总结付款字段。但我遇到错误,说“关键字As附近的语法不正确”。我在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

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

答案 2 :(得分:1)

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