0

我有一张桌子

ID  |   NAME    |   DEPT
1   |   A       |   D-1
2   |   B       |   D-1
3   |   C       |   D-2
4   |   D       |   D-3
5   |   E       |   D-1
6   |   F       |   D-3
7   |   G       |   D-4

现在我想获取结果

DEPT    |   COUNT(DEPT)
D-1     |   3
OTHERS  |   4

谁能帮我写这个查询?

4

3 回答 3

12

您需要使用和CASE对数据进行分组:D-1Others

select 
  case when dept = 'D-1' then 'D-1' else 'Others' end as Dept,
  count(*) as Total
from yt
group by case when dept = 'D-1' then 'D-1' else 'Others' end;

请参阅带有演示的 SQL Fiddle

于 2013-05-14T13:49:02.113 回答
0
SELECT 
     DEPT,
     COUNT (DEPT)AS [COUNT(DEPT)]
FROM(SELECT 
          (CASE DEPT WHEN 'D-1' THEN 'D-1' ELSE 'OTHERS' END) AS DEPT FROM test1) AS tbl
GROUP BY DEPT

请尝试上面的 sql 查询。

于 2013-05-14T15:33:44.553 回答
0

我猜你想要最大发生的部门与计数和其他部门与休息部门发生的总和。

好吧,您可以像下面那样做-

Select dept, count(*) cnt  
  from Table_name
 group by dept
having count(*) = ( select max(count(*)) from table_name group by dept)
union
select 'Other' dept, count(*) cnt 
  from table_name 
 where dept not in ( select dept 
                       from table_name 
                      group by dept 
                     having count(*) = ( select max(count(*)) 
                                           from table_name 
                                          group by dept
                                        )
                   )

我希望这就是你要找的..

于 2013-05-14T13:54:55.107 回答