履歴テーブルからピボットされた結果セットを作成する次の 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