作者jonce007 (汪汪)
看板Database
標題[SQL ] 語法求教,多欄位值如何有條件變成多筆row
時間Mon Sep 5 16:51:45 2016
資料庫版本:mysql 5.x
內容/問題描述: 將不為空白的欄位們變成多筆資料
表格a內,有三組no&amt
其中第一組 no1,amt1必有資料,
第二及第三組可能有值也可能空白
table a
-------------------------------------
id date no1 amt1 no2 amt2 no3 amt3
-- ------ --- ---- --- ---- --- ----
1 160901 001 2 002 12
2 160902 010 3
3 160903 021 6 022 4 022 2
------------------------------------
如何能自己join自己展開成:
id date no amt
-- ------ --- ----
1 160901 001 2
1 160901 002 12
2 160902 010 3
3 160903 021 6
3 160903 022 4
3 160903 028 2
目前想不出來,轉時用union替代
select id, date , no1 as no, amt1 as amt from a where ....
union
select id, date , no2 as no, amt2 as amt from a where ... and no2<>''
union
select id, date , no3 as no, amt3 as amt from a where ... and no3<>''
求SQL前輩先進們提示方向
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 61.216.136.100
※ 文章網址: https://www.ptt.cc/bbs/Database/M.1473065508.A.D44.html
→ meteor09887: 感覺你的問題用union就可以解了 09/06 12:26
→ meteor09887: 只是我不太懂為什麼要<>'' 09/06 12:26
→ jonce007: 空=沒資料不必展開。union要掃table三次,希望一次就好 09/06 18:49