我有兩個表用戶和出勤。我希望在特定時間間隔內獲得所有用戶的出勤率,即使用戶在某些日期(如公共假期)沒有出勤率,...
我使用 generate_series 來獲取所有日期,但是在加入和分組時,我只得到沒有出席的日期的單個值。
User table:
id | name | phone
1 | arun | 123456
2 | jack | 098765
Attendance table:
id | user_id | ckeck_in | check_out
11 | 2 | 2021-12-30 07:30:00 | 2021-12-30 16:00:00
21 | 1 | 2021-12-28 09:18:00 | 2021-12-28 17:45:00
所以如果我需要讓所有用戶在 2021 年 12 月出勤,我想要這樣
final_result:
user_id | name | date | check_in | check_out
1 | arun | 2021-12-01 | null | null
2 | jack | 2021-12-01 | null | null
1 | arun | 2021-12-02 | null | null
2 | jack | 2021-12-02 | null | null
...
1 | arun | 2021-12-28 | 2021-12-28 09:18:00 | 2021-12-28 17:45:00
2 | jack | 2021-12-28 | null | null
...
1 | arun | 2021-12-30 | null | null
2 | jack | 2021-12-30 | 2021-12-30 07:30:00 | 2021-12-30 16:00:00
PS:一個用戶一天可以有多個check_in和check_out。
提前致謝!
uj5u.com熱心網友回復:
您可以將 across join與 a 一起使用left join:
select t.*, a.check_in, a.check_out from
(select u.*, v from users u
cross join generate_series('2021-12-01', '2021-12-31', interval '1 day') v) t
left join attendance a on date(a.check_in)= date(t.v) and t.id = a.user_id
見演示。
uj5u.com熱心網友回復:
首先生成所需月份的系列。然后你可以使用left join.
select distinct user_id, name, md.date, case when date::date=check_in::date then
check_in else null end as check_in, case when date::date=check_out::date then
check_out else null end as check_out from month_data md, attendance_table a
left join user_table u on u.id=a.user_id order by date, user_id;
在這里提琴
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/413590.html
標籤:
下一篇:如何每月為每個id創建一行?
