i am trying to count the number of a weekday in a month just from a date.
My goal is the expectation column. Any idea how I can achieve it with a SQL script?
Question posted in PostgreSQL
The official documentation can be found here.
The official documentation can be found here.
2
Answers
It is unclear whether the
Weekday
column is part your input or just part of your output. But you did say just from a date so I will assume it is output (Why id needs repeating I do not know). You can get the day name from the to_char() function. Then use that in the Window functionrow_number() over()
. (see here, here and here)The CTE is used strictly as a data generator. See demo
FYI. It is best with an international audience to use the ISO 8601 date format yyyy-mm-dd. It is unambiguous regardless of local conventions. If your days had not exceeded 12 we could not know which format (mm-dd-yyyy or dd-mm-yyyy) you used.
You can calculate how many full weeks has been passed since the start of the month and add 1 to the result. This is the index number of day of week.
Full example: