SQL:如何在分组后对每个 VARCHAR 列进行合并?

鲍里斯奎特

使用下表:

id: integer| col_1: VARCHAR| col_2: VARCHAR | col_3: VARCHAR
------------------------------------------------------------
      1    |       'a'     |       'b'      |       null 
      2    |       null    |       'b'      |       'c'
      3    |       'd'     |       'e'      |       null
      4    |       null    |       'e'      |       'f'     

我想得到以下结果:

'a' | 'b' | 'c'
'd' | 'e' | 'f'

我试过这个查询:

SELECT colaesce(t.col_1), colaesce(t.col_2), coalesce(t.col_3)
FROM ( select * from table ) t 
INNER JOIN table ON t.col_2 = table.col_2;

我是 SQL 的新手,我将不胜感激!

乌拉斯

尝试这样的事情UNION

询问

;with cte as(
    select [rn] = row_number() over(
        partition by t.[cols]
        order by t.[col_val]
    ), *
    from(
        select [col_1] [col_val], 'col_1' [cols]
        from [your_table_name]
        where [col_1] is not null
        union
        select [col_2], 'col_2'
        from [your_table_name]
        where [col_2] is not null
        union
        select [col_3], 'col_3'
        from [your_table_name]
        where [col_3] is not null
    )t
)
select 
max(case [cols] when 'col_1' then [col_val] end) [col_1],
max(case [cols] when 'col_2' then [col_val] end) [col_2],
max(case [cols] when 'col_3' then [col_val] end) [col_3]
from cte
group by [rn];

在这里找到演示

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章