Skip to content
Advertisement

Grouping the result set based on conditions

I am calculating Age of a user based on his date of birth.

This gives me the UserId and his age.

Now I want to group this result.

How many users are in 30’s, How many users in 40’s and how many users in their 50’s.. need the count of users with their age groups

If the user is > 0 and less than 30 he should be grouped to 20’s

If the user is >= 30 and < 40 then he should be added to 30’s list, same with 40’s and 50’s

Can this be achieved without creating any temp table?

Advertisement

Answer

I believe this will get you what you want.

Anything < 30 will be placed in the ’20’ group. Anything >= 50 will be placed in the ’50’ group.

If they are 30-39 or 40-49, they will be placed in their appropriate decade group.

Placing the logic into CROSS APPLY makes it easier to reuse the logic within the same query, this way you can use it in SELECT, GROUP BY, ORDER BY, WHERE, etc, without having to duplicate it. This could also be done using a cte, but in this scenario, this is my preference.


Update:

You asked in the comments how it would be possible to show a count of 0 when no people exist for an age group. In most cases the answer is simple, LEFT JOIN. As with everything, there’s always more than one way to bake a cake.

Here are a couple ways you can do it:

The simple left join, take the query from my original answer, and just do a left join to a table. You could do this in a couple ways, CTE, temp table, table variable, sub-query, etc. The takeaway is, you need to isolate your User table somehow.

Simple Sub-query method, nothing fancy. Just stuck the whole query into a sub-query, then left joined it to our new lookup table.

This would be the exact same thing as using a cte:

Choosing between the two is purely preference. There’s no performance gain to using a CTE here.


Bonus:

If you wanted to table drive your groups and also have 0 counts, you could do something like this…though I will warn you to be careful using APPLY operators because they can be tricky with performance sometimes.

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