I am looking for Postgresql Query to implement something like this.
I have to distinctly divide employee table on base of week and then get count of employees added on the a week days.
Example ::
Week | Sunday | Monday | Tueday | Wednesday | Thrusday | Friday | Saturday | Total |
11/26/2023 - 12/02/2023 | 27 | 26 | 27 | 25 | 27 | 27 | 28 | 187 |
12/03/2023 - 12/09/2023 | 27 | 28 | 29 | 26 | 27 | 27 | 27 | 191 |
12/10/2023 - 12/16/2023 | 27 | 0 | 0 | 0 | 0 | 0 | 0 | 27 |
Column Explaination :
Week Column : [Start Date of the Week] - [End Date of the Week]
Sunday Column : Count of Employees Added on Sunday.
Monday Column : Count of Employees Added on Monday.
...
Total Column : Total Number of Employee on that Week.
Tables :
"Employee"
"Id" | "Name" | "Department" | "JoiningEpoch" | "JoiningDate" | "CreatedEpoch" |
1 | Robin | Developer | 1702706400 | 2023-12-16 00:00:00 | 1702706400 |
2 | Emp2 | HR | 1702965600 | 2023-12-09 00:00:00 | 1702965600 |
3 | Emp3 | DevOps | 1701237600 | 2023-11-29 00:00:00 | 1701237600 |
2
Answers
To get the count of employees added on each weekday for each week, you can use the
date_trunc()
function to group the employees by week and weekday, and then use thecount()
function to count the number of employees in each group. Something like this:See if it works!
You could use an aggregate
filter
clause to get day counts in separate columns, shift from ISO8601 Monday week start back one day to see your week ranges start on Sundays by subtracting1
and useto_char()
or set yourDateStyle
setting to achieve the desired date format: Demo at db<>fiddleThere’s also a
crosstab()
function intablefunc
extension that can pivot results this way automatically.