Mysql计数具有特定属性的行

时间:2016-10-05 02:34:06

标签: mysql select count distinct

所以,这是我的表:

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. 如何选择然后计算所有在A和B购物的人,然后
  2. 仅限A和B?
  3. A OR B BUT NO OTHER?
  4. D只?
  5. 在我的例子中,预期的结果是:(1)John + Pamela,(2)John,(3)John(4)Nick

2 个答案:

答案 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

在此进行第二次查询演示:

SQLFiddle

答案 1 :(得分:2)

我希望使用group byhaving来处理这些查询:

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;