Skip to content

Instantly share code, notes, and snippets.

@kevinwucodes
Created October 17, 2018 22:15
Show Gist options
  • Save kevinwucodes/7e6c944bf745cb56f3231848bd715b01 to your computer and use it in GitHub Desktop.
Save kevinwucodes/7e6c944bf745cb56f3231848bd715b01 to your computer and use it in GitHub Desktop.
sql - learn row_number() with case when
select
ranked = case
when color <> 'black' then
row_number() over (partition by
case when color <> 'black' then 1 end
,person
order by (select null)
)
else null
end
,*
from (
values
(1, 'kevin', 'blue')
,(2, 'kevin', 'black')
,(3, 'owen', 'blue')
,(4, 'aria', 'red')
,(5, 'aria', 'pink')
,(6, 'wendy', 'orange')
,(7, 'wendy', 'green')
) favoriteColors (id,person,color)
order by person, color
/*
ranked id person color
-------------------- ----------- ------ ------
1 5 aria pink
2 4 aria red
NULL 2 kevin black
1 1 kevin blue
1 3 owen blue
1 7 wendy green
2 6 wendy orange
(7 row(s) affected)
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment