繁体   English   中英

在SQL Server中选择2个不同的计数

[英]select 2 different count in sql server

我需要从具有几列(数字,颜色等)的表中选择前20000,并且我需要在一个查询中从这些20000中获取红色的计数和蓝色的计数。

我知道如果我在临时表中插入前20000,然后从临时表中选择红色的计数,然后从临时表中选择蓝色的计数,我就能得到我想要的东西,但是我需要在一个查询中进行操作。

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

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 inner.color, count(*) from 
(select top 20000 [number], color from [profile]) inner
group by inner.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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM