簡體   English   中英

有條件地將列名映射到行值

[英]Conditionally mapping column names to row values

假設我們有一個表,其中我們有一個用於郵政編碼的字段,其余的是二進制字段(1或NULL),其名稱對應於不同的地方。 例如,想象該表有201個字段,第一個字段標題為“郵政編碼”,包含郵政編碼,后者是200個二進制值字段,標題為城市名稱:芝加哥,紐約,休斯頓等。

假設第一行包含郵政編碼11373.雖然可以使用coalesce來查找第一個非空值並返回“紐約”,但另一個值如“Elmhurst”也可能是真的。

zip_code  new_york  chicago  elmhurst  dover  maspeth
10001        1        NULL     NULL    NULL    NULL
07801       NULL      NULL     NULL     1      NULL
11373        1        NULL      1      NULL     1

目標是將列名映射到每個相應的郵政編碼,並獲得如下輸出:

zip_code    city
 10001     new_york
 07801     dover
 11373     new_york
 11373     elmhurst
 11373     maspeth

任何幫助深表感謝。

這是SQL UNPIVOT的一個很好的用例:

SELECT unpvt.*
FROM 
    #x UNPIVOT (v FOR statename IN (new_york, chicago,elmhurst, dover, maspeth)) AS unpvt

一種方法使用union all

select zip_code, 'New York' as city from t where new_york = 1
union all
select zip_code, 'Chicago' as city from t where chicago = 1
union all
. . .

暫無
暫無

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

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