Where can I learn (and more importantly practice) the over/partition by clause?
Performing complex data partitioning when using PARTITION BY in SQL Server - Stack Overflow
Good places to learn SQL from? Datacamp not great
I need help using partition by
By adding the next (lead) account_status, you can then check if the status was OPEN then CLOSED.
select count(distinct account_id) cnt from ( select * ,lead(account_status, 1) OVER(ORDER BY date ASC) AS next_status from #temp ) a where account_status = 'OPEN' and next_status = 'CLOSED'
You can switch it around to find CLOSED then OPEN.
select count(distinct account_id) cnt from ( select * ,lead(account_status, 1) OVER(ORDER BY date ASC) AS next_status from #temp ) a where account_status = 'CLOSED' and next_status = 'OPEN'More on reddit.com
Videos
I don't know if there's a way to avoid using PERCENT_RANK() multiple times, but one way to do achieve this result without the unions would be with a CASE expression.
SELECT [Id]
,[Name]
,[Score]
,[Type]
,[Pool]
,[Rank] =
CASE [Pool]
WHEN 3 THEN PERCENT_RANK() OVER (PARTITION BY [Type], [Pool] ORDER BY [Score] DESC)
WHEN 2 THEN PERCENT_RANK() OVER (PARTITION BY [Type], CASE WHEN [Pool] >= 2 THEN 1 END ORDER BY [Score] DESC)
WHEN 1 THEN PERCENT_RANK() OVER (PARTITION BY [Type] ORDER BY [Score] DESC)
END
FROM @Dinky
ORDER BY [Type], [Pool], [Score] DESC;
Just remove the = sign and and create a second helper column after. Also no offense but the naming conventions and way you use SQL is just well not efficient. The fact you even unioned anything in this is beyond me. This is a simple query to write and you massively over complicated it. What's the point of writing CTEs and using unions? You literally just join correctly. In 10 years I literally have NEVER unioned in a CTE. Also not sure why you are using parameters etc.