在传播列时将所有行转换为一行

时间:2015-11-21 06:13:00

标签: sql-server tsql

我有这张桌子。

+-------+-------+--------+------+--------+
| Level | Entry |  Code  | Name | Value  |
+-------+-------+--------+------+--------+
| L1    |   111 | Item_1 | pcs  |   1    |
| L2    |   222 | Item_2 | ctn  |   6    |
+-------+-------+--------+------+--------+

我想查询一下。

+---------+--------+--------+---------+---------+--------+--------+---------+
| L1Entry | L1Code | L1Name | L1Value | L2Entry | L2Code | L2Name | L2Value |
+---------+--------+--------+---------+---------+--------+--------+---------+
|     111 | Item_1 | pcs    |       1 |     222 | Item_2 | ctn    |       6 |
+---------+--------+--------+---------+---------+--------+--------+---------+

可以通过

完成
;with L1 AS
(select Entry As L1Entry, Code As L1Code, Name As L1Name, Value As L1Value
from table
where Level = 'L1')
, L2 AS
(select Entry As L2Entry, Code As L2Code, Name As L2Name, Value As L2Value
from table
where Level = 'L2')
select * from L1
outer apply L2

在表现方面有没有比这更好的方法?

1 个答案:

答案 0 :(得分:2)

你的问题太复杂了。这是一个简单的连接,我认为性能将是相同的:

select * 
from table t1
join table t2 on t1.level = 'l1' and t2.level = 'l2'