我编写了一个查询,为这个例子选择了让我们说10 rows
。
+-----------+------------+
| STORENAME | COMPLAINTS |
+-----------+------------+
| Store1 | 4 |
| Store7 | 2 |
| Store8 | 1 |
| Store9 | 1 |
| Store2 | 1 |
| Store3 | 1 |
| Store4 | 1 |
| Store5 | 0 |
| Store6 | 0 |
| Store10 | 0 |
+-----------+------------+
我如何显示TOP 3
行但将剩余的行roll up
放入名为"其他" ,它将所有Complaints
加在一起?
所以像这样:
+-----------+------------+
| STORENAME | COMPLAINTS |
+-----------+------------+
| Store1 | 4 |
| Store7 | 2 |
| Store8 | 1 |
| Other | 4 |
+-----------+------------+
那么上面发生了什么,是显示top3
然后将剩余行的投诉添加到名为other 的行中
我已经耗尽了所有资源,无法找到解决方案。如果这有意义,请告诉我。
我创建了上述表格的SQLfiddle,如果可能的话可以编辑:)
希望这是可能的:)
谢谢, 麦克
答案 0 :(得分:1)
这样的事可能有效
select *, row_number() over (order by complaints desc) as sno
into #temp
from
(
SELECT
a.StoreName
,COUNT(b.StoreID) AS [Complaints]
FROM Stores a
LEFT JOIN
(
SELECT
StoreName
,Complaint
,StoreID
FROM Complaints
WHERE Complaint = 'yes') b on b.StoreID = a.StoreID
GROUP BY a.StoreName
) as t ORDER BY [Complaints] DESC
select storename,complaints from #temp where sno<4
union all
select 'other',sum(complaints) as complaints from #temp where sno>=4
答案 1 :(得分:1)
我使用双重聚合和row_number()
执行此操作:
select (case when seqnum <= 3 then storename else 'Other' end) as StoreName,
sum(numcomplaints) as numcomplaints
from (select c.storename, count(*) as numcomplaints,
row_number() over (order by count(*) desc) as seqnum
from complaints c
where c.complaint = 'Yes'
group by c.storename
) s
group by (case when seqnum <= 3 then storename else 'Other' end) ;
从我所看到的情况来看,您并不需要stores
中的任何其他信息,所以此版本只是将该表格保留下来。