使用case语句将多行连接到单个列中

时间:2018-07-10 11:13:00

标签: sql concatenation case group-concat vertica

我必须用分布在多行上的逗号分隔值来连接一列。 基于行号,我必须合并文本列。 例如,文本列中的row_num 2值应为AB,BC

输入

select * from mytable where date > 2018-01-03 and date < 2018-01-06 ;

所需的输出:

Name.   Date      Identifier     Text Row_num   Val
Charles 08/07/18 30565   AB    1       2
Charles 08/07/18     30565   BC    2       4
Charles 08/07/18     30565   CD    3       6
Charles 08/07/18     30565   EF    4   3
Charles 08/07/18     30565   FG    5.  4
Charles 08/07/18     30565   GH    6       5

使用查询:

Name    Date    Identifier  Text              Row_num        Val
Charles 08/07/18      30565     AB                  1         2
Charles 08/07/18      30565     AB,BC               2         4
Charles 08/07/18      30565     AB,BC,CD                3         6
Charles 08/07/18      30565     AB,BC,CD,EF         4         3
Charles 08/07/18      30565     AB,BC,CD,EF,FG      5         4
Charles 08/07/18      30565     AB,BC,CD,EF,FG,GF   7         5

此查询的问题在于它在“文本”列中为row_num 2,3,4,5,7提供了Null值。因此无法获得所需的输出

SELECT 
    Name,
    Date,
    ,Identifier
    MAX(CASE WHEN Row_nnum = 1 THEN Text END)  ||
    MAX(CASE WHEN Row_nnum = 2  THEN ', ' || Text ELSE '' END) ||
    MAX(CASE WHEN Row_nnum = 3  THEN ', ' || Text ELSE '' END) ||
    MAX(CASE WHEN Row_nnum = 4  THEN ', ' || Text ELSE '' END) ||
    MAX(CASE WHEN Row_nnum = 5  THEN ', ' || Text ELSE '' END) ||
    MAX(CASE WHEN Row_nnum = 6  THEN ', ' || Text ELSE '' END) ||
    MAX(CASE WHEN Row_nnum = 7  THEN ', ' || Text ELSE '' END)
    SUM(val)
FROM TABLE 
GROUP BY 1,2,3;

1 个答案:

答案 0 :(得分:0)

只需将该条件添加到CASE

SELECT Name, Date, Identifier,
       (MAX(CASE WHEN Row_nnum = 1 THEN Text END)  ||
        MAX(CASE WHEN Row_nnum = 2 AND Text IS NOT NULL THEN ', ' || Text ELSE '' END) ||
        MAX(CASE WHEN Row_nnum = 3 AND Text IS NOT NULL THEN ', ' || Text ELSE '' END) ||
        MAX(CASE WHEN Row_nnum = 4 AND Text IS NOT NULL THEN ', ' || Text ELSE '' END) ||
        MAX(CASE WHEN Row_nnum = 5 AND Text IS NOT NULL THEN ', ' || Text ELSE '' END) ||
        MAX(CASE WHEN Row_nnum = 6 AND Text IS NOT NULL THEN ', ' || Text ELSE '' END) ||
        MAX(CASE WHEN Row_nnum = 7 AND Text IS NOT NULL THEN ', ' || Text ELSE '' END)
       ),
      SUM(val)
FROM TABLE 
GROUP BY 1, 2, 3;