【问题标题】:Single SQL query for getting count based of 2 condition in same table基于同一表中的 2 个条件获取计数的单个 SQL 查询
【发布时间】:2021-04-21 00:12:34
【问题描述】:

我有这样的数据

现在我需要一个查询来获取信息为“是”的 id 计数和同时为“是”和“否”的 id 计数

单个查询:

SELECT COUNT(id) FROM table WHERE info = 'yes'

SELECT COUNT(id) FROM table WHERE info = 'yes' AND info = 'No'

自从

Id having Yes are 7 (1,2,3,4,5,6,7)
and Id having and Yes and No both vaules are only 3 (1,4, 6) 
it should give me id_as_yes = 7 and id_as_yes_no = 3

【问题讨论】:

  • 您的预期结果是什么?
  • 既然 ID 有 Yes 是 7 (1,2,3,4,5,6,7) 并且 Id 有 Yes 和 No 两个值都只有 3 (1,4, 6) 它应该给我 id_as_yes = 7 和 id_as_yes_no = 3

标签: sql sql-server dml


【解决方案1】:

您可以使用聚合和窗口函数来做到这一点:

SELECT DISTINCT 
       SUM(MAX(CASE WHEN info = 'yes' THEN 1 ELSE 0 END)) OVER () id_as_yes,
       COUNT(CASE WHEN COUNT(DISTINCT info) = 2 THEN 1 END) OVER () id_as_yes_no
FROM tablename
GROUP BY id

请参阅demo
结果:

> id_as_yes | id_as_yes_no
> --------: | -----------:
>         7 |            3

【讨论】:

【解决方案2】:

您需要条件聚合。

Select id, 
       Count(case when info = 'y' then 1 end) as y_count,
       Count(case when info = 'y' and has_n = 1 then 1 end) as yn_count
  From (SELECT id, info,
               Max(case when info = 'no' then 1 end) over (partirion by id) as has_n
         From your_table) t

【讨论】:

  • 在 600 万条数据上不起作用并且执行速度也很慢
【解决方案3】:

您可以在没有子查询的情况下执行此操作。这依赖于观察到“否”的 id 数量仅为:

count(distinct id) - count(distinct case when info = 'yes' then id end)

对于“是”的数量也是如此。所以,两者兼有的数字是 id 的数量减去 no only 的数量减去 yes only 的数量:

select count(distinct case when info = 'yes' then id end) as num_yeses,
       (count(distinct id) -
        (count(distinct id) - count(distinct case when info = 'yes' then id end)) -
        (count(distinct id) - count(distinct case when info = 'no' then id end))
       )
from t;
    

【讨论】:

    【解决方案4】:

    这应该可以解决问题...它绝对不是高效或优雅的,但没有空值聚合警告

    dbFiddle link

    Select
        (select select count(distinct id) from mytest where info = 'yes') as yeses
        ,(select count(distinct id) from mytest where info = 'no' and id in (select distinct id from mytest where info = 'yes' )) as [yes and no]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-08-04
      • 1970-01-01
      • 2016-07-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-08
      • 1970-01-01
      相关资源
      最近更新 更多