如何选择在一段时间内每月工作的用户?

时间:2017-07-19 05:42:02

标签: mysql database oracle

您如何修改此查询以返回给我,一年中所有12个月都工作过的所有用户ID?

SELECT extract(month from Date_worked) as Month,user_id FROM Users WHERE
 Date_worked >= '01/JAN/16' and Date_worked < '01/JAN/17'

这回复给我这样的事情:

MONTH - USER_ID
1        12
2        12
3        11
3        12
4        11
4        12
5        12
6        12
7        12
8        12
9        12
10       12
11       12
12       12   
...

在这种情况下,查询应该只返回USER_ID 12,因为它与所有12个月相关联。

2 个答案:

答案 0 :(得分:1)

SELECT
    user_id
FROM Users
WHERE Date_worked >= '01/JAN/16' AND Date_worked < '01/JAN/17'
GROUP BY user_id
HAVING COUNT(*) = 12

如果用户可能有多个与给定月份关联的记录,则使用以下HAVING子句计算不同的月份:

HAVING COUNT(DISTINCT EXTRACT(month from Date_worked)) = 12

答案 1 :(得分:0)

SELECT extract(month from Date_worked) as Month,user_id
FROM Users GROUP BY user_id
HAVING COUNT(DISTINCT extract(month from Date_worked) ) = 12

尝试以上查询。