【问题标题】:Get count of ID for name-value pair when name doesn't exist当名称不存在时获取名称-值对的 ID 计数
【发布时间】:2013-10-21 23:16:14
【问题描述】:

在 mysql 中 - 像这样的表:

ID 名称 值

1 颜色 蓝色
1 重量 50
1种水果
2 颜色 红色
2 体重 40
3 颜色 黄色

我想获取名称/特征为“类型”的不同 ID 的计数以及不具有不同 ID 的计数。第一个(那些做的)很容易,因为它已定义,但如果我执行 select count(distinct ID) where name 'type' - ID 1 仍将是该计数的一部分,因为它具有其他行/属性 '类型'。

在本例中,distinct count = 'type' 的期望结果为 1(ID 1),distinct count 'type' 的期望结果为 2(ID 的 2 和 3)。

提前致谢。

【问题讨论】:

  • 如果您想要两个计数,为什么不简单地从组总数中减去具有Type 特征的组数?

标签: mysql sql tsql


【解决方案1】:

这类似于SQL Query User has one record in the table but not another one

您可以选择 id 不在子查询中查找具有类型的 id 的位置

select count(id) from table where id not in (select id from table where name = 'type')
group by id

【讨论】:

    【解决方案2】:

    对于这个特定的任务,您可以使用:

    select count(distinct ID) from table
    where ID in (select ID from table where name='type') --- this will give you count of IDs where type exists
    
    select count(distinct ID) from table
    where ID not in (select ID from table where name='type') -- this will give you count of IDs without type
    

    【讨论】:

      【解决方案3】:
      SELECT id FROM test GROUP BY id HAVING 
      CONCAT(",",CONCAT(GROUP_CONCAT(name), ","))
      NOT LIKE '%,Type,%'
      

      会给你所有没有Type的ID:http://sqlfiddle.com/#!2/30837/1

      (Concat 与, 确保您不会偶然匹配XType。)

      同时

      SELECT COUNT(id) AS count, GROUP_CONCAT(id) AS ids 
      FROM(SELECT id, count(name) as count FROM test 
      GROUP BY id HAVING CONCAT(",",CONCAT(GROUP_CONCAT(name), ","))
      NOT LIKE '%,Type,%') as temp;
      

      将为您提供所需的计数:http://sqlfiddle.com/#!2/30837/9

      【讨论】:

        【解决方案4】:
        SELECT CASE
                  WHEN Name='Type' THEN 'Type'
                  ELSE 'Non-Type'
               END Name
              ,ID
              ,COUNT(ID)
        FROM Stuff
        GROUP BY
             CASE
                  WHEN Name='Type' THEN 'Type'
                  ELSE 'Non-Type'
             END 
            ,ID
        

        SQLFiddle

        【讨论】:

          猜你喜欢
          • 2019-03-11
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-01-15
          • 1970-01-01
          • 1970-01-01
          • 2015-10-19
          • 2013-10-13
          相关资源
          最近更新 更多