如何从sql中的一列获取多个聚合数据

时间:2015-09-29 07:38:58

标签: sql sql-server

假设我有一张表

 days  count 
0 6
1 7
4 18
1 12
6 8
7 25
2 4
6 30
5 15

我希望结果为三列数据

day_range   total_count   above_threshold_count
  0-3          4                   1     (assuming threshold as 8)
  4-7          5                   2     (assuming threshold as 20) 

我能够一次只获得2个查询

select 
case when days <=3 then "0-3"
     when days <=7 then "4-7" end as day_range,
count(*)  from t1 
group by case when days <=3 then "0-3"
     when days <=7 then "4-7" end  

2 个答案:

答案 0 :(得分:2)

使用条件聚合:

SELECT
    CASE 
        WHEN days <=3 THEN '0-3'
        WHEN days <=7 THEN '4-7'
    END AS day_range,
    COUNT(*) AS total_count,
    SUM(
        CASE 
            WHEN days <=3 AND [count] > 8 THEN 1 
            WHEN days <=7 AND [count] > 20 THEN 1
        END
    ) AS above_treshold_count
FROM t1
GROUP BY
    CASE 
        WHEN days <=3 THEN '0-3'
        WHEN days <=7 THEN '4-7'
    END

答案 1 :(得分:0)

请尝试以下SQL SELECT语句

;with cte as (
select
    case when days between 0 and 3 then '0-3' else '4-7' end as day_range,
    case 
        when days between 0 and 3 then
            case when count >= 8 then 1 else 0 end
        else 
            case when count >= 20 then 1 else 0 end
    end as above_threshold
from 
    DayCount
)
select
    day_range,
    count(*) total_count,
    sum(above_threshold) above_threshold_count
from cte
group by day_range