我希望优化以下 SQL 语句,该语句从历史表中创建透视结果集。这可能已经是最高效的方式了,但我一直认为必须有一种更高效的方式来做到这一点。
我正在尝试优化的 SQL 语句
select Col1, Col2,
Max(case when TypeId = 1 then ColValue end) as Pivot1,
Max(case when TypeId = 2 then ColValue end) as Pivot2,
Max(case when TypeId = 3 then ColValue end) as Pivot3,
Max(case when TypeId = 4 then ColValue end) as Pivot4,
Max(case when TypeId = 5 then ColValue end) as Pivot5,
Max(case when TypeId = 6 then ColValue end) as Pivot6,
Max(case when TypeId = 7 then ColValue end) as Pivot7,
Max(case when TypeId = 8 then ColValue end) as Pivot8,
Max(case when TypeId = 9 then ColValue end) as Pivot9,
Max(case when TypeId = 10 then ColValue end) as Pivot10,
Max(case when TypeId = 11 then ColValue end) as Pivot11
from RowTable
group by Col1, Col2
更新:下面是表定义
CREATE TABLE dbo.RowTable (
Id int NOT NULL,
Col1 char(8) NOT NULL,
Col2 tinyint NOT NULL,
TypeId int NOT NULL,
ColValue datetime NOT NULL,
CreatedBy varchar(50) NOT NULL,
Rowstamp timestamp NOT NULL
)
LOCK DATAROWS
GO
ALTER TABLE dbo.RowTable
ADD CONSTRAINT ukRowTable
UNIQUE (Col1, Col2, TypeId)
WITH max_rows_per_page = 0, reservepagegap = 0