【问题标题】:SQL Counting rows with columns that satisfy a conditionSQL 计算具有满足条件的列的行
【发布时间】:2015-11-05 05:08:45
【问题描述】:

假设我有一个表格,其中 ID 列和内容填充了数据。

ID | Content
1  | a
1  | b
1  | c
2  | b
2  | a
3  | b

我想找到每个“a”、“b”和“c”中至少有一个的 ID,因此返回的表将是:

ID | Content
1  | a
1  | b
1  | c

【问题讨论】:

    标签: mysql sql


    【解决方案1】:

    使用条件 SUM 验证 group id 内部是否存在每个元素的 1 个或多个。

    然后选择DISTINCT ID, Content 以消除可能的重复项

    SELECT DISTINCT ID, Content
    From YourTable
    WHERE ID IN (SELECT ID
                 FROM YourTable
                 GROUP BY ID
                 HAVING SUM(case when Content = 'a' then 1 else 0 end) >= 1
                    AND SUM(case when Content = 'b' then 1 else 0 end) >= 1
                    AND SUM(case when Content = 'c' then 1 else 0 end) >= 1
                )
    

    【讨论】:

    • 我是否正确假设 SUM(case when Content = 'a' then 1 else 0 end) > 1 应该 = 1 或 > 0?
    • @CuriousCat 不知道你的表,所以不确定ID=1 是否可以重复。a 应该是=1 >=1
    【解决方案2】:
    select * from (
    where 
    Select ID ,SUM(case when Content = 'a' then 1 else 0 end) as sum_a ,UM(case when Content = 'b' then 1 else 0 end) as sum_b,
    SUM(case when Content = 'c' then 1 else 0 end) as sum_c
                 FROM table 
                 Group by  ID)x
                 where x.sum_a >1 or sum_b>1 or sum_c>1
    

    【讨论】:

      【解决方案3】:

      这是另一种方法,它检查每个 ID 一定数量的不同“内容”项。 Here 是指向此解决方案的 SQL Fiddle 的链接。

      select 
          id, 
          count(distinct(content)) 
        from tableX 
       group by id 
       having count(distinct(content)) = 3;
      

      【讨论】:

      • 如果 content 只有值 a,b,c 如果内容也允许 a,b,c,d,e,f 不允许,这也可以工作。
      猜你喜欢
      • 2015-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-05
      • 2013-10-14
      • 2020-03-07
      • 2020-04-09
      相关资源
      最近更新 更多