我的示例查询是:
SELECT
SUM(CASE WHEN tb.[CashStatus] = 0 AND tb.[CashPayMethod] = 0 THEN tb.[CashPayPrice] ELSE 0 END) AS [TotalCashPrice],
SUM(CASE WHEN tb.[CashStatus] = 0 AND tb.[CashPayMethod] = 10 THEN tb.[CashPayPrice] ELSE 0 END) AS [TotalPOSPrice]
FROM
mytable tb
结果是:
TotalCashPrice | TotalPOsPrice
---------------+----------------
41,000,000 | 12,000,000
我想将其更改为:
Value | Name
-----------------+--------------------
41,000,000 | TotalCashPrice
12,000,000 | TotalPOSPrice
谢谢大家。
答案 0 :(得分:1)
我将使用GROUP BY
并将CASE
表达式移至要聚合的列:
SELECT (CASE WHEN tb.CashPayMethod = 0 THEN 'TotalCashPrice'
WHEN tb.CashPayMethod = 10 THEN 'TotalPOSPrice'
END) as name,
SUM(tb.CashPayPrice) as value
FROM mytable tb
WHERE tb.CashStatus = 0 AND tb.CashPayMethod IN (0, 10)
GROUP BY tb.[CashPayMethod]
答案 1 :(得分:0)
这里一个简单的选择就是只做一个联合:
SELECT SUM(CashPayPrice) AS Value, 'TotalCashPrice' AS Name
FROM mytable
WHERE CashStatus = 0 AND CashPayMethod = 0
UNION ALL
SELECT SUM(CashPayPrice), 'TotalPOSPrice'
FROM mytable
WHERE CashStatus = 0 AND CashPayMethod = 10;
另一个选择是使用SQL Server的UNPIVOT
运算符。但是,如果您的实际问题没有比这大得多的话,那可能就太过致命了。
答案 2 :(得分:0)