我有一个考勤系统表(IN / OUT),这是一个示例数据。
ID | Date | Transaction
1 | 2016-03-21 06:04:55.000 | I
2 | 2016-03-21 06:04:55.000 | I
3 | 2016-03-21 06:04:55.000 | I
4 | 2016-03-21 06:04:55.000 | I
1 | 2016-03-21 17:04:55.000 | O
2 | 2016-03-21 17:04:55.000 | O
3 | 2016-03-21 17:04:55.000 | O
1 | 2016-03-22 06:04:55.000 | I
2 | 2016-03-22 06:04:55.000 | I
3 | 2016-03-22 06:04:55.000 | I
4 | 2016-03-22 06:04:55.000 | I
1 | 2016-03-22 17:04:55.000 | O
2 | 2016-03-22 17:04:55.000 | O
3 | 2016-03-22 17:04:55.000 | O
4 | 2016-03-22 17:04:55.000 | O
...........
我想要得到的是所有ID,我给出的每个日期都有IN和OUT交易,所以在我的例子中,如果我给3月21日和22日,我将获得ID 1-3,因为4没有3月21日的OUT事务。我尝试使用IN语句但不起作用,因为它检索在任何日期都有事务的所有ID。
答案 0 :(得分:0)
试试这个:
SELECT ID
FROM mytable
WHERE CAST([Date] AS Date) IN ('2016-03-21', '2016-03-22')
GROUP BY ID
HAVING COUNT(DISTINCT CASE
WHEN CAST([Date] AS Date) = '2016-03-21' THEN Transaction
END) = 2
AND
COUNT(DISTINCT CASE
WHEN CAST([Date] AS Date) = '2016-03-22' THEN Transaction
END) = 2