将同一表中的列按GROUP BY划分为两个别名列

时间:2019-06-20 18:28:41

标签: sql

我有这张桌子: table

我想知道是否有一些SQL查询返回如下所示: result

我尝试了一下,但是没有用:

SELECT Object, 
       SUM(CASE WHEN Key = 'A' THEN Qty END) As Key A, 
       SUM(CASE WHEN Key = 'B' THEN Qty END) As Key B
FROM tab

甚至添加了GROUP BY子句,但错误出在CASE子句

2 个答案:

答案 0 :(得分:1)

我期望这样的事情:

SELECT Object,
       SUM(CASE WHEN Key = 'A' THEN Qty END) As KeyA,
       SUM(CASE WHEN Key = 'B' THEN Qty END) As KeyB
FROM table  -- table won't work as a table name
GROUP BY object;

我添加了GROUP BY并修复了列别名。

答案 1 :(得分:0)

在执行汇总时在查询中添加分组依据

    SELECT Object, 
   SUM(CASE WHEN Key = 'A' THEN Qty END) As Key_A,
   SUM(CASE WHEN Key = 'B' THEN Qty END) As Key_B
    FROM table group by Object

您已经使用了列别名名称的空间,但我将其更改了