Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
MS SQL Server / pivot example
CREATE TABLE [dbo].[tTMP](
[Id] [int] NOT NULL,
[IdResp] [int] NULL,
[IdBranch] [int] NULL,
[IdPost] [int] NULL,
[CountWorks] [int] NULL,
[CountSub] [int] NULL,
CONSTRAINT [PK_tTmp] PRIMARY KEY CLUSTERED
( [Id] ASC
)WITH (PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]) ON [PRIMARY]
insert into tTMP values(1, 1, 1, 1, 12,10)
insert into tTMP values(2, 1, 1, 2, 15,8)
insert into tTMP values(3, 1, 1, 3, 5,3)
insert into tTMP values(4, 2, 1, 1, 10,8)
insert into tTMP values(5, 2, 2, 2, 8,7)
insert into tTMP values(6, 2, 2, 3, 2,1)
insert into tTMP values(7, 3, 2, 1, 3,2)
insert into tTMP values(8, 3, 2, 2, 2,1)
insert into tTMP values(9, 3, 2, 3, 5,2)
insert into tTMP values(10, 3, 2, 4, 12,10)
select IdResp, IdBranch, [1],[2],[3],[4]
from (select IdResp, IdBranch, IdPost, CountWorks from tTMP) as t
pivot (sum(CountWorks) for IdPost in ([1],[2],[3],[4])
) as pvt
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.