簡體   English   中英

將多個列名稱連接到1列SQL中

[英]Concatenate multiple column names into 1 column SQL

我在這里遇到小問題。 我有一張四列的桌子

Column1 | Column2 | Column3 | Column4
NULL.........NULL.........NULL.........NULL
ABC..........NULL..........XYZ...........NULL


列1,2和3可能有一些值或為空,列4為空
當column1,2或3中的任何一個都不為null時,我必須使用該列名更新column4。 我期待以下結果

Column1 | Column2 | Column3 | Column4
NULL.........NULL.........NULL.........NULL
ABC..........NULL..........XYZ...........Column1,Column3


誰能指導我如何實現這一目標。
任何幫助表示贊賞。 提前致謝。

使用一種情況來測試空值,並在其不為空時返回列名。 那里的東西是刪除您在字符串中第一個得到的多余逗號。

update YourTable 
set Column4 = stuff(case when Column1 is not null then ',Column1' else '' end +
                    case when Column2 is not null then ',Column2' else '' end +
                    case when Column3 is not null then ',Column3' else '' end, 1, 1, '')

SQL小提琴

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM