Skip to content
Advertisement

How to group by and select corresponding row values?

To start I am using SSMS 2018. I am trying to create a Common Table Expression to use in some code later. I need to get down to a single row per applicable quarter per person, I’ve tried using Havings/Group Bys and wheres but I can’t get the correct result set. What I have Currently is a table like this:

The Durable Key represents a person overtime.

The QuarterEndDateOfStartQuarter represents the first applicable quarter per some requirements, i.e. ate at least 10 cookies in one day during the quarter

The QuarterEndDate represents the current Quarter, up to 3 quarters after the QuarterEndDateOfStartQuarter

The TotalCookies represents the cookies since the beginning of the Start Quarter that have been eaten

The NumberofDays represents the number of days since the beginning of the Start Quarter that a cookie was eaten.

The data looks similar to this:

And what I want to end up with is a CTE that has person – quarter granularity rather than person – Start Quarter – quarter. So the table would have the columns :

Where if there are overlapping rows, the data would be pulled from the row corresponding to the earlier QuarterEndDateOfStartQuarter :

I feel like this should be straightforward but have been not been able to accomplish it.

Advertisement

Answer

Use row_number to order by the QuarterEndDateOfStartQuarter column partitioned by the key and the quarter. Then select the first ordered for each partition.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement