SQL选择前五个最近的行,并按特定列进行区分

时间:2017-04-06 15:59:00

标签: sql sql-server

好的,所以说我的名字appModelFlat下面有一张桌子,只有几百行。它没有日期字段,但我想找出最近创建的五个环境(EnvName)。只有14种可能的环境(EnvName)。但我想选择插入不同EnvName的五个最近插入的行。也就是说我想选择不同的EnvName(尽管不同的方式不是这样工作)最近的5行,我知道它们是最新的id。行越新,id越高。任何有关此查询的帮助将不胜感激。

id|AppName|EnvName|ServerTypeName|ServerId|OS     |OSVersion|CPU|Memory|ExtraStorage|MachineDesc   |
----------------------------------------------------------------------------------------------------
1 |ASB    |DEV    |App           |1       |Windows|7        |4  |4     |100         |ASB-DEV-App   |

----------------------------------------------------------------------------------------------------
5 |AMS    |DEV    |APP           |2       |RedHat |7.2      |4  |4     |50          |AMS-DEV-App   |

----------------------------------------------------------------------------------------------------
6 |SPB    |TST    |App           |1       |Windows|7        |2  |8     |50          |SPB-TST-App   |

----------------------------------------------------------------------------------------------------
7 |SBI    |TST    |Oracle        |1       |Solaris|11       |4  |8     |100         |SBI-TST-Oracle|

----------------------------------------------------------------------------------------------------

这是我的第一次尝试,虽然我不确定它是否正确。它确实给了我五个结果。

 SELECT  DISTINCT top 5  [ID] = ( SELECT TOP 1 [ID]  FROM [AppModelFlat] Y WHERE Y.[EnvName] = X.[EnvName])
            ,[AppName]= ( SELECT TOP 1 [AppName] FROM [AppModelFlat] Y WHERE Y.[EnvName] = X.[EnvName])
            ,[EnvName] 
            ,[ServerTypeName] = ( SELECT TOP 1 [ServerTypeName] FROM [AppModelFlat] Y WHERE Y.[EnvName] = X.[EnvName])
            ,[ServerId] = ( SELECT TOP 1 [ServerId] FROM [AppModelFlat] Y WHERE Y.[EnvName] = X.[EnvName])
            ,[OS] = ( SELECT TOP 1 [OS] FROM [AppModelFlat] Y WHERE Y.[EnvName] = X.[EnvName])
        FROM [AppModelFlat] X order by id desc

编辑:

预期结果。让我们说我只想选择前2名,因为我这里只给了5个参赛作品。我想取回以下内容。

5 |AMS    |DEV    |APP           |2       |RedHat |7.2      |4  |4     |50          |AMS-DEV-App   |

----------------------------------------------------------------------------------------------------
7 |SBI    |TST    |Oracle        |1       |Solaris|11       |4  |8     |100         |SBI-TST-Oracle|

因为我只有每个EnvName中的一个,并且每一行都有该行的最高Id编号。

2 个答案:

答案 0 :(得分:1)

使用row_number()获取每个EnvName的最新行,并仅从有序top 5获取Id desc

select top 5 *
from (
  select *
    , rn = row_number() over (partition by EnvName order by id desc)
  from appModelFlat 
  ) s
where rn = 1
order by id desc

top with ties版本:

select top 5 *
from (
  select top 1 with ties *
  from appModelFlat
  order by row_number() over (partition by EnvName order by id desc)
  ) s
order by id desc

答案 1 :(得分:0)

一个简单的子查询也可以解决这个问题:

SELECT      TOP 5 Id, AppName, EnvName, ServerTypeName, ServerId, OS
FROM        AppModelFlat Records
INNER JOIN  (SELECT EnvName,
                    MAX(Id) as Id
             FROM   AppModelFlat) Latest ON Records.Id = Latest.Id