1

我在下面的查询中遇到了一些问题。我正在尝试确定“类别”字段是 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

4

3 回答 3

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
于 2012-04-06T17:25:44.573 回答
1
SELECT *
FROM dbo.r_invoiceTable
PIVOT
( SUM(payment)
FOR category IN ([a],[b],[c])
) AS pivoted
于 2012-04-06T17:24:47.563 回答
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
于 2012-04-06T16:53:17.680 回答