关注数据库示例
id | date | customer | ...
-----------------------------------------
1 2016-07-05 1
2 2016-07-05 2
3 2016-07-06 1
4 2016-07-07 1
5 2016-07-07 2
我想在2016-07-07
选择2016-07-06
但不的所有客户。
起初,我以为我是使用WHERE
执行此操作的:
SELECT * FROM table
WHERE EXISTS ( SELECT * FROM table WHERE date = '2016-07-07' )
AND NOT EXISTS ( SELECT * FROM table WHERE date = '2016-07-06' )
GROUP BY customer
但由于WHERE
在 GROUP BY
之前执行了,结果只能为空 - table
位于2016-07-06
的记录。
所以,使用HAVING
,我该怎么做?我在查找HAVING
子句中的行存在时遇到困难。类似的东西:
SELECT * FROM table
GROUP BY customer
HAVING exists date '2016-07-07'
AND not exists date '2016-07-06'
答案 0 :(得分:1)
按customer
分组,并且只接受date
条目中至少有2016-07-07
个条目的2016-07-06
条目,<{1}}
SELECT customer
FROM your_table
GROUP BY customer
HAVING sum(date = '2016-07-07') > 0
AND sum(date = '2016-07-06') = 0
答案 1 :(得分:1)
SELECT customer FROM table t
WHERE EXISTS ( SELECT * FROM table t1
WHERE date = '2016-07-07' AND t.customer = t1.customer)
AND NOT EXISTS ( SELECT * FROM table t2
WHERE date = '2016-07-06' AND t.customer = t2.customer)
GROUP BY customer