如何在SQL中将多行合并为一行?

时间:2019-02-21 04:00:22

标签: mysql sql database postgresql select

我有一个特殊的表,该表包含以下列-

Table

属性ID可以具有1-6中的6个可能值。该表将包含所有客户的条目。客户的每一行都包含1-6个值的条目。

现在我要实现的目标如下-

Desired Output

我执行以下查询-

SELECT CUST_ID,
        CASE WHEN "ATTR ID"=1 THEN "ATTR_VALUE" END AS ATTR_ID_1,
        CASE WHEN "ATTR ID"=2 THEN "ATTR_VALUE" END AS ATTR_ID_2,
        CASE WHEN "ATTR ID"=3 THEN "ATTR_VALUE" END AS ATTR_ID_3,
        CASE WHEN "ATTR ID"=4 THEN "ATTR_VALUE" END AS ATTR_ID_4,
        CASE WHEN "ATTR ID"=6 THEN "ATTR_VALUE" END AS ATTR_ID_5,
        CASE WHEN "ATTR ID"=7 THEN "ATTR_VALUE" END AS ATTR_ID_6

FROM "TABLE_NAME" where CUST_ID='20002123'

这可以很好地产生6列,但最终也会创建3行-

Output

我应该旋转桌子吗?

谢谢

2 个答案:

答案 0 :(得分:1)

您非常亲密:

SELECT CUST_ID,
    max(CASE WHEN "ATTR ID"=1 THEN "ATTR_VALUE" END) AS ATTR_ID_1,
    max(CASE WHEN "ATTR ID"=2 THEN "ATTR_VALUE" END) AS ATTR_ID_2,
    max(CASE WHEN "ATTR ID"=3 THEN "ATTR_VALUE" END) AS ATTR_ID_3,
    max(CASE WHEN "ATTR ID"=4 THEN "ATTR_VALUE" END) AS ATTR_ID_4,
    max(CASE WHEN "ATTR ID"=6 THEN "ATTR_VALUE" END) AS ATTR_ID_5,
    max(CASE WHEN "ATTR ID"=7 THEN "ATTR_VALUE" END) AS ATTR_ID_6

FROM "TABLE_NAME" where CUST_ID='20002123'
Group by cust_id;

此外,您可以查看枢轴。

答案 1 :(得分:1)

您可以使用GROUP BY CUST_ID进行汇总,以将多行作为单行。

尝试像下面那样更改查询。

SELECT CUST_ID, 
       Max(ATTR_ID_1) AS ATTR_ID_1, 
       Max(ATTR_ID_2) AS ATTR_ID_2, 
       Max(ATTR_ID_3) AS ATTR_ID_3, 
       Max(ATTR_ID_4) AS ATTR_ID_4, 
       Max(ATTR_ID_5) AS ATTR_ID_5, 
       Max(ATTR_ID_6) AS ATTR_ID_6 
FROM   (SELECT CUST_ID, 
               CASE WHEN "ATTR ID" = 1 THEN "ATTR_VALUE"  END AS ATTR_ID_1, 
               CASE WHEN "ATTR ID" = 2 THEN "ATTR_VALUE"  END AS ATTR_ID_2, 
               CASE WHEN "ATTR ID" = 3 THEN "ATTR_VALUE"  END AS ATTR_ID_3, 
               CASE WHEN "ATTR ID" = 4 THEN "ATTR_VALUE"  END AS ATTR_ID_4, 
               CASE WHEN "ATTR ID" = 6 THEN "ATTR_VALUE"  END AS ATTR_ID_5, 
               CASE WHEN "ATTR ID" = 7 THEN "ATTR_VALUE"  END AS ATTR_ID_6 
        FROM   "TABLE_NAME" 
        WHERE  CUST_ID = '20002123')T 
GROUP  BY CUST_ID