SQL自定义按值分组

时间:2015-09-04 13:15:11

标签: sql tsql sql-server-2008-r2

好的,我所拥有的是一系列县。我想做的是按县获得客户数量。但是,我只需要三个主要县,然后将其他所有类别分组为“其他”类别。

select county,COUNT(*)
from person
where person_id in (select distinct person_id from person_encounter)
and create_timestamp >= CONVERT(datetime,'2015-08-01')
and create_timestamp <= CONVERT(datetime,'2015-08-31')
group by county

我拥有的东西让我对所有县的数量都很好。但是如何将额外内容分组为“其他”

2 个答案:

答案 0 :(得分:2)

试试这个

select 
    CASE county
        WHEN 'County1' THEN 'County1'
        WHEN 'County2' THEN 'County2'
        WHEN 'County3' THEN 'County3'
     ELSE 'Other' END AS County
    ,COUNT(*)
from person
where person_id in (select distinct person_id from person_encounter)
    and create_timestamp >= CONVERT(datetime,'2015-08-01')
    and create_timestamp <= CONVERT(datetime,'2015-08-31')
group by  
    CASE county
        WHEN 'County1' THEN 'County1'
        WHEN 'County2' THEN 'County2'
        WHEN 'County3' THEN 'County3'
     ELSE 'Other' END ;

答案 1 :(得分:0)

如果一个UNION of 2查询1st =你的主要3个县,第二个=一切不是你的主要3个县

select * from student 
where 
(
   (if studentId is not null then  studentId='x')
   else
   (firstName='abc' and age > 26)
)