使用 SQL 服务器通过自连接转置 table
Transposing a table by self-join using SQL Server
我正在尝试找到正确的查询来动态转置 table/matrix 的第一行并将它们与其他值并排放置,
表 1:
ID | System1 | System2 | System3 | System4 |
1 | | Admin | Lunch | Training|
2 | INFO | INFO | INFO | INFO |
3 | INFO | INFO | INFO | INFO |
4 | IN | IN | IN | IN |
查询结果应如下:
ID | System1 | System1_1| System2 | System2_2 | System3 | System3_3 | System4 | System4_4 |
2 | INFO | | INFO | Admin | INFO | Lunch | INFO | Training |
3 | INFO | | INFO | Admin | INFO | Lunch | INFO | Training |
4 | IN | | IN | Admin | IN | Lunch | IN | Training |
如您所见,我将顶行值转置到相关的新列中。这样,这些值并排属于同一条记录。
如何通过自连接实现此目的?
使用自联接,您可以:
select t.id,
t.system1, t1.system1 as system1_1,
t.system2, t1.system2 as system2_1,
t.system3, t1.system3 as system3_1,
t.system4, t1.system4 as system4_1
from mytable t
cross join mytable t1
where t.id > 1 and t1.id = 1
我正在尝试找到正确的查询来动态转置 table/matrix 的第一行并将它们与其他值并排放置,
表 1:
ID | System1 | System2 | System3 | System4 |
1 | | Admin | Lunch | Training|
2 | INFO | INFO | INFO | INFO |
3 | INFO | INFO | INFO | INFO |
4 | IN | IN | IN | IN |
查询结果应如下:
ID | System1 | System1_1| System2 | System2_2 | System3 | System3_3 | System4 | System4_4 |
2 | INFO | | INFO | Admin | INFO | Lunch | INFO | Training |
3 | INFO | | INFO | Admin | INFO | Lunch | INFO | Training |
4 | IN | | IN | Admin | IN | Lunch | IN | Training |
如您所见,我将顶行值转置到相关的新列中。这样,这些值并排属于同一条记录。
如何通过自连接实现此目的?
使用自联接,您可以:
select t.id,
t.system1, t1.system1 as system1_1,
t.system2, t1.system2 as system2_1,
t.system3, t1.system3 as system3_1,
t.system4, t1.system4 as system4_1
from mytable t
cross join mytable t1
where t.id > 1 and t1.id = 1