Sql Server group by,count查询

时间:2015-03-05 11:24:51

标签: sql sql-server

我有以下查询

select COUNT(mc_owner) as nbr , mc_owner
from [dbo].[full] 
where (date_reception > '01-01-2015')
group by (mc_owner)
order by nbr desc

这告诉我

  
      
  • 20000 element1
  •   
  • 10000 element2
  •   
  • 10000 element3
  •   
  • 10000 element4
  •   

我需要只有两个结果element1和其他组合在元素上

之类的东西
  
      
  • element1 20000
  •   
  • 其他30000
  •   

感谢您的帮助

2 个答案:

答案 0 :(得分:5)

使用CASE表达式执行此操作,如下所示:

SELECT
    COUNT(*) as nbr,
    CASE mc_owner WHEN 'Element1' THEN 'Element1' ELSE `Others` END as Owner
FROM [dbo].[full] 
WHERE (date_reception > '01-01-2015')
GROUP BY CASE mc_owner WHEN 'Element1' THEN 'Element1' ELSE `Others` END
ORDER BY COUNT(*) DESC

我们的想法是提供一个表达式,根据'Element1'字段的值,评估您需要的两个值之一 - 即Othersmc_owner

答案 1 :(得分:0)

declare   @tt table(name varchar(10),id int)

insert into @tt(name,id)values ('element1',2000)
insert into @tt(name,id)values ('element2',2000)
insert into @tt(name,id)values ('element3',2000)
insert into @tt(name,id)values ('element4',2000)


;WITH CTE AS
(
select ROW_NUMBER()OVER(Partition by ID ORDER BY ID,name) RN, * from @tt 

)
select NAME,ID from CTE
where RN = 1
UNION ALL
select 'Others' as NAME,SUM(id) as ID 
from CTE
where RN >1