我有一张表
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
任何人都可以帮我写这个查询吗?
答案 0 :(得分:12)
您需要使用CASE
按D-1
和Others
对数据进行分组:
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;
答案 1 :(得分: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
)
)
我希望这就是你要找的......
答案 2 :(得分: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查询。