2017-05-19 58 views
-2

參考下表:SQL:如何在組之後的每個VARCHAR列上創建一個Coalesce?

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和我將不勝感激任何幫助!

+0

向我們展示你嘗試 – Backs

+0

@Backs'SELECT colaesce(COL_1),colaesce(COL_2),聯合(col_3) FROM(SELECT * FROM表)t INNER JOIN table ON ta = table.a;' – boriskuete

回答

0

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]; 

Find demo here

+0

非常感謝@ @llas,這個乾淨的答案。只是爲了確定我理解了查詢過程。首先,您創建了表格的透視圖,然後使用行號函數將其分配給具有相同列名稱的所有行相同的Id ** [rn] **。最後你在每個分區上做了一個分組。 – boriskuete

相關問題