【问题标题】:select 2 different count in sql server在 sql server 中选择 2 个不同的计数
【发布时间】:2015-04-15 16:00:51
【问题描述】:

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

我知道如果我在临时表中插入前 20000 个,然后从临时表中选择红色计数,然后从临时表中选择蓝色计数,我可以得到我想要的,但我需要这样做在一个查询中。

我尝试了以下方法,但它给了我每个数字的计数,我需要总数..

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

输出:

颜色 |计数

红色 | 15000

蓝色 | 5000

【问题讨论】:

  • 向我们展示您的预期输出及其格式。
  • @wewestthemenace 你可以找到更新的我的问题

标签: sql sql-server sql-server-2008 count sql-server-2012


【解决方案1】:

您可以使用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]

【讨论】:

    【解决方案2】:

    您可以使用嵌套查询:

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

    【讨论】:

      【解决方案3】:
      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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-02-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-06-13
        • 1970-01-01
        相关资源
        最近更新 更多