Skip to content

Instantly share code, notes, and snippets.

@kevinwucodes
Created October 18, 2018 16:48
Show Gist options
  • Save kevinwucodes/7fb1d95e21b7f134894154a29c219ee2 to your computer and use it in GitHub Desktop.
Save kevinwucodes/7fb1d95e21b7f134894154a29c219ee2 to your computer and use it in GitHub Desktop.
sql - learn pivoting
--;with q as (
-- select id, color, intensity
-- from (
-- values
-- (1,'blue',4)
-- ,(2,'red',5)
-- ,(3,'blue',7)
-- ,(4,'blue',1)
-- ,(5,'yellow',3)
-- ) colors (id, color, intensity)
--)
-- --select * from q
--select *
--from (
-- select id, color, intensity
-- from q
--) y
--pivot (
-- sum(intensity)
-- for color in ([blue], [red], [yellow])
--) pt
-----------------------
select color, sum(intensity)
from (
values
(1,'blue',4)
,(2,'red',5)
,(3,'blue',7)
,(4,'blue',1)
,(5,'yellow',3)
) t (id, color, intensity)
group by color
;with colors as (
select color, intensity
from (
values
(1,'blue',4)
,(2,'red',5)
,(3,'blue',7)
,(4,'blue',1)
,(5,'yellow',3)
) t (id, color, intensity)
)
select *
from colors
pivot (
--count(id)
sum(intensity)
for color in (
[blue]
,[red]
,[yellow]
,[black]
)
) pt
/*
color
------ -----------
blue 12
red 5
yellow 3
(3 row(s) affected)
blue red yellow black
----------- ----------- ----------- -----------
12 5 3 NULL
(1 row(s) affected)
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment