SQL分组前10个最高的多列表达式

时间:2014-10-29 16:09:20

标签: sql tsql sql-order-by

以下内容返回每个前10个foo的最高条形值,按该值从上到下排序: SELECT top 10 foo, MAX(bar) AS Count FROM tbl GROUP BY foo ORDER BY Count DESC;

如何扩展此模式以配合多个分组列表达式? 即返回每个foo的最高bar1,bar2,bar3 ..值,全部按DESC排序。

根据我的场景更新,请找到以下查询和相应的输出: select top 10 Name as Rg_name, no as Rg_no, MAX(IOPS_Read) as MAX_Riops, MAX(IOPS_Write) as MAX_Wiops, MAX(IOPS_ReadWrite) as MAX_RWiops from rgs GROUP BY Name, no ORDER BY MAX_Riops DESC, MAX_Wiops DESC, MAX_RWiops DESC

Rg_name           Rg_no  MAX_Riops MAX_Wiops  MAX_RWiops

VMWARE_RG12       34     5444      117        5461
VM_RG_02          2      5436      567        5512
VM_RG_05          11     5327      545        5349
VM_RG_11          14     3623      644        3631
VMWARE_VDI_RG7    25     2530      908        2630
VMWARE_RG_4 16    2182   401       2189       107
EXCHANGE_RG_1     23     1891      734        2151
VM_RG_01    47    1801   2338      3586       69
VMWARE_RG11 33    1696   242       1712       24
VMWARE_RG_SP_02   18     1504      507        1512

从这里我只获得了排名前10位的Rg_name以及具有最高值的相应指标,如MaxRiops,MAXWiops等。这里的问题是我发现只有MAXRiops列被命名为DESC。我想在DESC顺序中有其他列。

2 个答案:

答案 0 :(得分:0)

您的意思是您想要选择更多列吗? 即。

Select top 10 foo, Max(bar) Count1, Max(ABC) count2
from tbl
Group By foo, bar
Order By Count1 desc

答案 1 :(得分:0)

使用ROW_NUMBER,您可以获得每个foo的前10个bar1,bar2值。

 with cte 
  as
  (
  select  foo, 
          bar1,
          bar2,
          ROW_NUMBER() over ( partition by foo order by bar1 desc) seq1,  
          ROW_NUMBER() over (  partition by foo order by bar2 desc) seq2
  from Table1
  )
  select foo, bar1, bar2 from cte where seq1 <=10 or seq2 <=10
  order by bar1 desc, bar2 desc