【问题标题】:Mysql counting row with specific attributes具有特定属性的Mysql计数行
【发布时间】:2017-02-13 08:15:00
【问题描述】:

所以,这是我的桌子:

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 或 B 但没有其他?
  4. 仅限 D 吗?

在我的示例中,预期结果是:(1) John + Pamela, (2) John, (3) John (4) Nick

【问题讨论】:

    标签: mysql select count distinct


    【解决方案1】:

    在 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

    【讨论】:

    • 蒂姆和戈登的回答很好。对于一个新案例(3)A OR B 但没有其他案例怎么样?
    • 我已更新我的问题以涵盖更多案例。只在 D 怎么样?
    【解决方案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;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-21
      • 1970-01-01
      相关资源
      最近更新 更多