如何将 table 的链接列转换为 SQL 中的行?
How to convert linked columns of a table to rows in SQL?
我有一个table如下:
ID | Fileid1 | Fileid2 | Fileid3 | LanguageID1 | LanguageID2 | LanguageID3
---------------------------------------------------------------------------
1 | 123 | 256 | | a12 | a23 |
2 | 124 | | | a12 | |
这里的LanguageID1
对应Fileid1
,LanguageID2
对应Fileid2
,依此类推
我想将其转换为以下内容:
ID | Field | LangaugeID
1 | 123 | a12
2 | 256 | a23
3 | 124 | a12
我已经尝试在这两个字段上使用 UNPIVOT
,但它给出了所有列之间的关系。应该怎么做呢?
您可以使用联合:
select row_number() over(order by ID, Fileid) as ID,
Fileid,
LanguageID
from
(select ID, Fileid1 as Fileid, LanguageID1 as LanguageID from table_name
union all select ID, Fileid2 as Fileid, LanguageID2 as LanguageID from table_name
union all select ID, Fileid3 as Fileid, LanguageID3 as LanguageID from table_name) t
where Fileid is not null
你可以试试:
select id, Fileid, LanguageID
from (
select id,fileid1 as Fileid,LanguageID1 as LanguageID
from my_table
union all
select id,fileid2 as Fileid ,LanguageID2 as LanguageID
from my_table
union all
select id,fileid3 as Fileid ,LanguageID3 as LanguageID
from my_table
) as t1
where concat_ws('',Fileid,LanguageID) !=''
我有一个table如下:
ID | Fileid1 | Fileid2 | Fileid3 | LanguageID1 | LanguageID2 | LanguageID3
---------------------------------------------------------------------------
1 | 123 | 256 | | a12 | a23 |
2 | 124 | | | a12 | |
这里的LanguageID1
对应Fileid1
,LanguageID2
对应Fileid2
,依此类推
我想将其转换为以下内容:
ID | Field | LangaugeID
1 | 123 | a12
2 | 256 | a23
3 | 124 | a12
我已经尝试在这两个字段上使用 UNPIVOT
,但它给出了所有列之间的关系。应该怎么做呢?
您可以使用联合:
select row_number() over(order by ID, Fileid) as ID,
Fileid,
LanguageID
from
(select ID, Fileid1 as Fileid, LanguageID1 as LanguageID from table_name
union all select ID, Fileid2 as Fileid, LanguageID2 as LanguageID from table_name
union all select ID, Fileid3 as Fileid, LanguageID3 as LanguageID from table_name) t
where Fileid is not null
你可以试试:
select id, Fileid, LanguageID
from (
select id,fileid1 as Fileid,LanguageID1 as LanguageID
from my_table
union all
select id,fileid2 as Fileid ,LanguageID2 as LanguageID
from my_table
union all
select id,fileid3 as Fileid ,LanguageID3 as LanguageID
from my_table
) as t1
where concat_ws('',Fileid,LanguageID) !=''