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

wooyq4lh  于 2022-12-26  发布在  其他
关注(0)|答案(4)|浏览(174)

我有这样的数据

现在,我需要一个查询来获取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
2ic8powd

2ic8powd1#

您可以使用聚集和窗口函数执行此操作:

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
lvjbypge

lvjbypge2#

您需要条件聚合。

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
js4nwp54

js4nwp543#

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

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

对于肯定的数目也是如此,所以,两者都有的数目等于id的数目减去否定的数目再减去肯定的数目:

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;
ws51t4hk

ws51t4hk4#

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

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]

相关问题