Skip to content
Advertisement

SQL Server – convert date to weekday and count each instance of weekday in second column

Wondering how to select from a table:

I’d like to get a result table of two columns: weekday and the number of purchases of each weekday.

So far, I have something like this:

But this returns two Thursday rows and two weekend rows, because they are different weeks. How can I get it to only return 1 row for each Thursday and one for weekend?

Thanks

Advertisement

Answer

I am thinking:

This uses CROSS APPLY to define wkday once, so it can be used both in the SELECT and GROUP BY. Note that SQL Server has a function that returns the name of the week day. You don’t need a CASE expression for that.

EDIT:

If you want to count unique purchases, then use COUNT(DISTINCT):

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