将SQL行标题转换为第一列

时间:2018-11-13 21:50:33

标签: sql pivot transpose

转置以下查询结果的最短,最快,最简单的方法是什么?我希望第一列显示0-3和3-6。抱歉,但是如果我不伸出手,这几天就会让我感到困惑。预先感谢。

SELECT SUM (CASE WHEN CMAPR BETWEEN 0 AND 3 THEN 1 ELSE 0 END) AS [0-3],
       SUM (CASE WHEN CMAPR BETWEEN 3.01 AND 6 THEN 1 ELSE 0 END) AS [3-6]
FROM TBL

enter image description here

当前结果:

1 个答案:

答案 0 :(得分:0)

使用聚合:

SELECT (CASE WHEN CMAPR >= 0 AND CMAPR <=3 THEN '0-3'
             WHEN CMAPR <= 6 THEN '3-6'
             ELSE 'Other'
        END) AS grp, COUNT(*)
FROM tbl
GROUP BY (CASE WHEN CMAPR >= 0 AND CMAPR <=3 THEN '0-3'
               WHEN CMAPR <= 6 THEN '3-6'
               ELSE 'Other'
          END);

唯一的缺点是,如果没有行,它将不会返回一个组。

您只需执行以下操作即可取消查询的旋转:

SELECT v.*
FROM (SELECT SUM (CASE WHEN CMAPR BETWEEN 0 AND 3 THEN 1 ELSE 0 END) AS [0-3],
             SUM (CASE WHEN CMAPR BETWEEN 3.01 AND 6 THEN 1 ELSE 0 END) AS [3-6]
      FROM TBL
     ) x CROSS APPLY
     (VALUES ('[0-3]', [0-3]), ('[3-6]', [3-6])) v(which, val);