如何更改输出类型?

时间:2018-10-07 15:03:39

标签: sql sql-server tsql

我的示例查询是:

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

谢谢大家。

3 个答案:

答案 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)

您可以使用UNPIVOT获得所需的输出:

declare @tmp table(TotalCashPrice int, TotalPOsPrice int) 

insert into @tmp values (41000000, 12000000)

select u.[Value], u.[Name]
from @tmp s 
unpivot 
( 
    [Value] 
    for [Name] in ([TotalCashPrice], [TotalPOsPrice]) 
) u

结果:

enter image description here

如果原始列名(TotalCashPrice,TotalPOsPrice)可以更改数量,则需要动态TSQL。