Most of the examples that I've seen are more complex, so I guess I posted something simple to fully understand the concept of pivot
.
declare @yt TABLE
(
Id int,
Dept varchar(10),
[Day] int,
[Counter] int
);
INSERT INTO @yt
(
ID, Dept, [Day], [Counter]
)
VALUES
(102, 'DeptA', 20170704, 96),
(102, 'DeptP', 20170704, 223),
(103, 'DeptA', 20170704, 84),
(103, 'DeptW', 20170704, 43);
select *
from
(
select id, dept, [day], [Counter]
from @yt
) src
pivot
(
sum([Counter])
for Dept in ([DeptA], [DeptP], [DeptW])
) piv;
From my understanding, the code within Pivot
does the following: 1) aggregates the column selected (sum([counter])
), pivots the column in for Dept
and then does a group by
of the rest of the columns that are not specified (ID
and Day
).
Would I be able to add two sums? Or is this something beyond the scope of the pivot functionality? The following generates an error:
declare @yt TABLE
(
Id int,
Dept varchar(10),
[Day] int,
[Counter] int,
Sales int
);
INSERT INTO @yt
(
ID, Dept, [Day], [Counter], Sales
)
VALUES
(102, 'DeptA', 20170704, 96, 12),
(102, 'DeptP', 20170704, 223, 5),
(103, 'DeptA', 20170704, 84, 9),
(103, 'DeptW', 20170704, 43, 11);
select *
from
(
select id, dept, [day], [Counter], sales
from @yt
) src
pivot
(
sum([Counter]), ([sales])
for Dept in ([DeptA], [DeptP], [DeptW])
) piv;
Wanted to add that this question was helpful in understanding the pivot tables.