SQL枢轴列的动态排列

时间:2019-10-15 17:16:35

标签: sql tsql

我的数据-

CREATE TABLE Tbl1 (State varchar(max), Value int)
INSERT INTO Tbl1 VALUES 
('A',10),
('B',20),
('C1',30),
('C3',40),
('D',50),
('C2',70),
('E',60);

场景/问题-我想要以C开头的任何状态最后堆叠在一起的状态。如果添加了新状态(例如C2),则查询应该能够检测并插入C2作为C1和C3之间的列。如果添加了状态E,则应将其添加为D之后的列。

必需的输出-

+----+----+----+----+----+----+----+
| A  | B  | D  | E  | C1 | C2 | C3 |
+----+----+----+----+----+----+----+
| 10 | 20 | 50 | 60 | 30 | 70 | 40 |
+----+----+----+----+----+----+----+

1 个答案:

答案 0 :(得分:1)

示例

Declare @SQL varchar(max) = '
Select *
From Tbl1 A
Pivot (sum(Value) 
  For [State] in (' + Stuff((Select ',' + QuoteName([State]) 
                               From ( Select top 10000 [State] 
                                       From  Tbl1 
                                       Group By [State] 
                                       Order By Len([State]),[State]
                                     ) A For XML Path('')),1,1,'')  + ') 
                  ) p
'

--Print @SQL
Exec(@SQL);

返回

A   B   D   E   C1  C2  C3
10  20  50  60  30  70  40