【问题标题】:Issue with Sql query: count distinct row values relative to other row valueSql 查询的问题:计算相对于其他行值的不同行值
【发布时间】:2015-07-17 10:34:14
【问题描述】:

我有下表:

name        category    posts
------------------------------
Client A    01          5348
Client A    05          2584
Client B    02          105
Client C    14          10558
Client C    16          511
Client D    01          4863
Client D    01          1823

现在我想选择那些行:

  • 客户端仅存在于一个类别中。这意味着客户端 B 和客户端 D 仍然可以使用。

  • 这个类别是“01”。所以最终期望的输出是:

    Client D    01          4863
    Client D    01          1823
    

我想到的查询:

SELECT name, category, posts
FROM exampletable
WHERE (count number of present distinct categories for each name = '1' AND category='01');

问题是我不知道如何将“count number of present distinct categories for each name”翻译成正确的 sql 代码。谁能帮我解决这个问题?

【问题讨论】:

    标签: mysql sql select count


    【解决方案1】:

    您可以使用子查询来实现:

    Select e.name, e.category, e.posts from exampletable e
    where e.name not in
    (select e1.name from exampletable e1 where e.name = e1.name and e.category <> e1.category) 
    and e.category = '01'
    

    说明:子查询将返回所有与类别不存在一对一关系的名称,因此可以使用NOT IN 将其删除,并可以应用进一步的过滤器使用AND category = '01'

    【讨论】:

      【解决方案2】:

      经过测试和验证。

      create table #t (
       name varchar(100),
       category varchar(2),
       posts int
      );
      
      insert into #t
      select
      'Client A', '01',  5348
      union all select
      'Client A', '05',  2584
      union all select
      'Client B', '02',  105
      union all select
      'Client C', '14',  10558
      union all select
      'Client C', '16',  511
      union all select
      'Client D', '01',  4863
      union all select
      'Client D', '01',  1823;
      
      select
          name,
          category,
          posts
      from
          #t
      where name in
          (
              select
                  name
              from
                  #t
              group by
                  name
              having
                  1 = count(distinct category)
          ) 
          and '01' = category;
      

      输出:

      Client D    01  4863
      Client D    01  1823
      

      【讨论】:

        猜你喜欢
        • 2018-08-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-10-14
        • 1970-01-01
        相关资源
        最近更新 更多