【问题标题】:SQL combining queriesSQL 组合查询
【发布时间】:2021-01-21 18:57:16
【问题描述】:

目前,我在同一张表上有两个单独的查询,检查有多少不同的项目。在第一个查询中,我对较大列表中不同项目的数量感兴趣,而在第二个查询中,我只对该列表的一个子集感兴趣。最终我会加入这两个输出。

 SELECT count(distinct a.item) as items
 FROM table a
 WHERE a.item in ('01','02','03','04','05','06','07','08','09','10')


 SELECT count(distinct a.item) as specific_items
 FROM table a
 WHERE a.item in ('01','02')

是否可以将其压缩为单个查询?将来我想看看列表的其他子集,而不是添加更多查询和连接更多表,我认为必须有一种方法来优化它的可读性和时间。

【问题讨论】:

    标签: sql count distinct where-clause


    【解决方案1】:

    您可以使用条件聚合:

    select 
        count(distinct a.item) as items,
        count(distinct case when a.item in ('01', '02') then a.item end) as specific_items
    from table a
    where a.item in ('01', '02', '03', '04', '05', '06', '07', '08', '09', '10')
    

    注意:item_id 真的是字符串数据类型吗?如果它是一个数字,那么我建议将它与数字进行比较。如果它是一个整数,那么您可以将where 子句简化如下:

    select 
        count(distinct a.item) as items,
        count(distinct case when a.item in (1, 2) then a.item end) as specific_items
    from table a
    where a.item between 1 and 10
    

    根据您未披露的数据库,可能有更简洁的解决方案可用。例如,Postgres 和 SQLite 支持标准的filter 子句,它允许您将第二个计数重写为:

    count(distinct a.item) filter(where a.item in (1, 2)) as specific_items
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-09-28
      • 2012-06-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-20
      • 2012-08-30
      相关资源
      最近更新 更多