次のようなものかもしれません:
最初のテスト データ:
CREATE TABLE #tbl (AccountManager VARCHAR(100), Action VARCHAR(100),Count INT) INSERT INTO #tbl VALUES ('Joe','Client Negotiation',10), ('Bloggs','Closing',1), ('Aunty','Email',12), ('Marie','Preparing Contract',32)
プレ>列が静的であることがわかっている場合。次に、これを行うことができます:
SELECT AccountManager, ISNULL([Client Negotiation],0) AS [Client Negotiation], ISNULL([Closing],0) AS [Closing], ISNULL([Email],0) AS [Email], ISNULL([Preparing Contract],0) AS [Preparing Contract] FROM ( SELECT tbl.AccountManager, tbl.Action, tbl.Count FROM #tbl AS tbl ) AS p PIVOT ( SUM([Count]) FOR [Action] IN([Client Negotiation],[Closing],[Email],[Preparing Contract]) ) AS pvt
プレ>それ以外の場合は、次のような動的なピボットを行う必要があります:
最初に一意の列名:
DECLARE @cols VARCHAR(MAX), @colsWithIsNull VARCHAR(MAX) ;WITH CTE AS ( SELECT ROW_Number() OVER(PARTITION BY tbl.Action ORDER BY tbl.Action) AS iRank, tbl.Action FROM #tbl AS tbl ) SELECT @cols = COALESCE(@cols + ','+QUOTENAME(Action), QUOTENAME(Action)), @colsWithIsNull=COALESCE(@colsWithIsNull + ',ISNULL('+QUOTENAME(Action)+',0) AS '+QUOTENAME(Action), 'ISNULL('+QUOTENAME(Action)+',0) AS '+QUOTENAME(Action)) FROM CTE WHERE iRank=1
プレ>次に、このような動的ピボット:
DECLARE @query NVARCHAR(4000)= N'SELECT AccountManager, '[email protected]+' FROM ( SELECT tbl.AccountManager, tbl.Action, tbl.Count FROM #tbl AS tbl ) AS p PIVOT ( SUM([Count]) FOR [Action] IN('[email protected]+') ) AS pvt' EXECUTE(@query)
プレ>次に、私の場合、一時テーブルを削除します:
DROP TABLE #tbl
プレ>