所以,这是我的表:
Id | name | Store
001 | John | A
001 | John | A
001 | John | A
001 | John | B
001 | John | B
001 | John | D
002 | Bob | B
002 | Bob | C
003 | Dave | C
004 | Pamela | A
004 | Pamela | B
004 | Pamela | C
005 | Nick | D
005 | Nick | D
005 | Nick | D
在我的例子中,预期的结果是:(1)John + Pamela,(2)John,(3)John(4)Nick
答案 0 :(得分:3)
在A 和 B(以及可能在其他地方)购物的人的姓名:
SELECT name
FROM yourTable
GROUP BY name
HAVING SUM(CASE WHEN Store = 'A' THEN 1 END) > 0 AND -- A is present
SUM(CASE WHEN Store = 'B' THEN 1 END) > 0 -- B is present
A 或 B(但没有其他人)的人的姓名:
SELECT name
FROM yourTable
GROUP BY name
HAVING (SUM(CASE WHEN Store = 'A' THEN 1 END) > 0 OR -- A is present
SUM(CASE WHEN Store = 'B' THEN 1 END) > 0) AND -- B is present
SUM(CASE WHEN Store NOT IN ('A', 'B') THEN 1 END) = 0 -- only A or B
在A和B购物 的人的姓名:
SELECT name
FROM yourTable
GROUP BY name
HAVING SUM(CASE WHEN Store = 'A' THEN 1 END) > 0 AND -- A is present
SUM(CASE WHEN Store = 'B' THEN 1 END) > 0 AND -- B is present
COUNT(DISTINCT Store) = 2 -- only A and B are present
仅在商店D购物的人的姓名:
SELECT name
FROM yourTable
GROUP BY name
HAVING SUM(CASE WHEN Store <> 'D' THEN 1 END) = 0 -- only store D
在此进行第二次查询演示:
答案 1 :(得分:2)
我希望使用group by
和having
来处理这些查询:
select name
from t
group by name
having sum(store = 'A') > 0 and
sum(store = 'B') > 0;
这使得在两家商店购物的人都可以。如果你只想要那两个商店而不是其他商店:
select name
from t
group by name
having sum(store = 'A') > 0 and
sum(store = 'B') > 0 and
sum(store not in ('A', 'B')) = 0;