Performing complex data partitioning when using PARTITION BY in SQL Server - Stack Overflow
How does PARTITION BY in a window function work with the GROUP BY clause?
Where can I learn (and more importantly practice) the over/partition by clause?
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.
Hello.
I am taking a class on SQL and today's class was about analytic functions like RANK, DENSE_RANK, etc. I understand how GROUP BY works when using aggregation functions and how PARTITION BY works when using an analytic function on the entire result set.
What I get stumped by is when GROUP BY and PARTITION BY are combined in a SQL query.
For example,
SELECT customer_name, customer_state, SUM(sales_dollar), RANK() OVER (PARTITION BY customer_state ORDER BY SUM(sales_dollar) DESC) FROM ... GROUP BY customer_name, customer_state
I would appreciate if someone could elucidate with an example how this combination of GROUP BY and PARTITION BY works.