我有一个代码,可以输出一长串每个名称的工单总数,并按总数,名称和数量进行排序:
;with cte as (
SELECT [Name],
[Emergency],
count([Emergency]) as [CountItem]
FROM tableA
GROUP BY [Name], [Emergency])
select Name,[Emergency],[Count],SUM([CountItem]) OVER(PARTITION BY Name) as Total from cte
order by Total desc, Name, [CountItem] desc
但我只想获得总数最多的前10个名称,如下所示:
+-------+-------------------------------+-------+-------+
| Name | Emergency | Count | Total |
+-------+-------------------------------+-------+-------+
| PLB | No | 7 | 15 |
| PLB | No Hot Water | 4 | 15 |
| PLB | Resident Locked Out | 2 | 15 |
| PLB | Overflowing Tub | 1 | 15 |
| PLB | No Heat | 1 | 15 |
| GG | Broken Lock - Exterior | 6 | 6 |
| BOA | Broken Lock - Exterior | 2 | 4 |
| BOA | Garage Door not working | 1 | 4 |
| BOA | Resident Locked Out | 1 | 4 |
| 15777 | Smoke Alarm not working | 3 | 3 |
| FP | No air conditioning | 2 | 3 |
| FP | Flood | 1 | 3 |
| KB | No electrical power | 2 | 3 |
| KB | No | 1 | 3 |
| MEM | Noise Complaint | 3 | 3 |
| ANG | Parking Issue | 2 | 2 |
| ALL | Smoke Alarm not working | 2 | 2 |
| AAS | No air conditioning | 1 | 2 |
| AAS | Toilet - Clogged (1 Bathroom) | 1 | 2 |
+-------+-------------------------------+-------+-------+
注意:我不追求唯一值。正如您从上面的示例中看到的那样,它从一个很长的表中获得前10名。
我想为每个名称分配一个行ID,以便上面的所有PLB的行ID为1,GG = 2,BOA = 3,...
因此,在我的最终选择中,我只会添加where子句where row id <= 10
。我已经尝试过ROW_NUMBER() OVER(PARTITION BY Name ORDER BY Name)
,但它会为其遇到的每个唯一名称分配1。
答案 0 :(得分:2)
您可以尝试以下方法:
;with cte as (
SELECT [Name],
[Emergency],
count([Emergency]) as [CountItem]
FROM tableA
GROUP BY [Name], [Emergency]),
ct as (
select Name,[Emergency],[Count],SUM([CountItem]) OVER(PARTITION BY PropertyName) as Total from cte
),
ctname as (
select dense_rank() over ( order by total, name ) as RankName, Name,[Emergency],[Count], total from ct )
select * from ctname where rankname < 11
答案 1 :(得分:-1)
假设查询为MySQL,则需要使用LIMIT
algorithmic complexity attacks
如果查询是SQL,则需要使用TOP
https://dev.mysql.com/doc/refman/5.5/en/limit-optimization.html