按SQL中的一系列值进行分组

Isa*_*c E 5 sql sql-server

我的表如下:

id | label_id | value
1  | 1        | 500
2  | 1        | 600
3  | 1        | 900
4  | 1        | 10000
5  | 1        | 300
6  | 2        | ...
....................
Run Code Online (Sandbox Code Playgroud)

现在,我想生成一个查询结果,例如:

caption        | count
Less than 500  | 1
500 to 900     | 2
Above 900      | 1
Run Code Online (Sandbox Code Playgroud)

简而言之,我正在尝试对结果集进行分区,以便按一系列值进行分组.有任何想法吗?

分区组显然是预先定义的,这意味着我提前知道我的分区方案应该是:<500,500-900,900 +等等.

谢谢!

Joe*_*lli 15

select sum(case when value < 500 then 1 else 0 end) as [less than 500],
       sum(case when value >= 500 and value <= 900 then 1 else 0 end) as [500 to 900],
       sum(case when value > 900 then 1 else 0 end) as [above 900]
    from YourTable
Run Code Online (Sandbox Code Playgroud)

编辑:从下面的评论中解决Dalen的关注,并以问题中给出的确切格式提供输出:

select 'less than 500' as Caption, count(*) as Count
    from YourTable
    where value < 500
union all
select '500 to 900' as Caption, count(*) as Count
    from YourTable
    where value >= 500 and value <= 900
union all
select 'above 900' as Caption, count(*) as Count
    from YourTable
    where value > 900
Run Code Online (Sandbox Code Playgroud)

而且,对于SQL Server 2005+,您可以通过将UNPIVOT与原始查询一起使用来改进:

select Caption, Count
    from (select sum(case when value < 500 then 1 else 0 end) as [less than 500],
                 sum(case when value >= 500 and value <= 900 then 1 else 0 end) as [500 to 900],
                 sum(case when value > 900 then 1 else 0 end) as [above 900]
              from YourTable) t
unpivot (Count for Caption in ([less than 500], [500 to 900], [above 900])) p
Run Code Online (Sandbox Code Playgroud)