select sql 服务器中有 2 个不同的计数

select 2 different count in sql server

我需要从我的 table 中 select 前 20000 个,它有多个列(数字、颜色等...),我需要得到红色的计数和红色的计数在一个查询中从这 20000 个中提取蓝色。

我知道我可以得到我想要的,如果我在温度 table 中插入前 20000 个,然后 select 从温度 table 中计算红色,然后 select 蓝色从临时计数 table,但我需要在一个查询中完成。

我试过下面的但它给了我每个数字的计数,我需要总数..

SELECT  top 20000 [number], count(color)
FROM [profile]
group by number
having color='red'

输出:

颜色 |计数

红色 | 15000

蓝色 | 5000

您可以使用 iif :

select  top 20000 [number]
     , sum(iif([color] = 'red', 1, 0) as red_count
     , sum(iif([color] = 'blue', 1, 0) as blue_count
from [profile]
group by [number]

case:

select  top 20000 [number]
     , sum(case when [color] = 'red' then 1 else 0 end) as red_count
     , sum(case when [color] = 'blue' then 1 else 0 end) as blue_count
from [profile]
group by [number]

编辑。更新问题后,我想您的查询应该如下所示:

select t.[color]
     , count(t.[color])
from (select  top 20000 [color] from [profile]) t
group by t.[color]
SELECT  top 20000 [number], count(color) as count_total, 
        sum(case when color='red' then 1 else 0 end) as count_red, 
        sum(case when color='blue' then 1 else 0 end) as count_blue
FROM [profile]
group by number

您可以使用嵌套查询:

select inner.color, count(*) from 
(select top 20000 [number], color from [profile]) inner
group by inner.color