TSQL Reversing查询将cols显示为行

时间:2017-08-18 13:49:45

标签: tsql sql-server-2012

以下查询将为我提供

Active  Inactive
3       1

SELECT
SUM(CASE WHEN Active = 'True' THEN 1 ELSE 0 END) AS Active,
SUM(CASE WHEN Active = 'False' THEN 1 ELSE 0 END) AS Inactive
FROM Events

我想得到它:

Status    Count
Active    3
Inactive  1

我该怎么反过来?

1 个答案:

答案 0 :(得分:2)

无需透视结果集,您可以使用简单的GROUP BY

SELECT CASE Active WHEN 'True' THEN 'Active'
                   WHEN 'False' THEN 'Inactive'
       END AS Status
      ,COUNT(*) AS Count
FROM Events
WHERE Active IN ('True', 'False')
GROUP BY CASE Active WHEN 'True' THEN 'Active'
                   WHEN 'False' THEN 'Inactive'
       END;