单个 SQL 查询基于同一 table 中的 2 个条件获取计数

Single SQL query for getting count based of 2 condition in same table

我有这样的数据

现在我需要一个查询来获取 Info 为 'Yes' 的 id 计数以及 'yes' 和 'no'

中的 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

您可以使用聚合和 window 函数来完成:

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

您需要条件聚合。

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

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

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

同意的数量也类似。所以,两者兼有的数字是ids的数量减去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;
    

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

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]