Created
April 28, 2017 08:55
-
-
Save kohav/d797dc454b7d69cff32f0ddb4e926e05 to your computer and use it in GitHub Desktop.
MS SQL Server / pivot example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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