选择第二个MAX值

时间:2016-02-05 12:14:58

标签: sql sql-server max

我想从tblTask​​s(JobID,ItemName,ContentTypeID)中选择第二高的值

这就是我的意思。我打赌它可以做得更容易,但我不知道如何。

SELECT Max(JobID)    AS maxjobid,
       Max(ItemName) AS maxitemname,
       ContentTypeID
FROM   
      (SELECT JobID, ItemName, ContentTypeID
      FROM tblTasks Ta
      WHERE JobID NOT IN
            (SELECT MAX(JobID)
            FROM tblTasks Tb
            GROUP BY ContentTypeID)
            ) secmax

     GROUP BY secmax.ContentTypeID

4 个答案:

答案 0 :(得分:2)

我猜你想要这样的东西。

SELECT  JobID AS maxjobid,
        ItemName AS maxitemname,
        ContentTypeID
FROM    (SELECT JobID,
                ItemName,
                ContentTypeID,
                ROW_NUMBER() OVER (PARTITION BY ContentTypeID ORDER BY JobID DESC) Rn
         FROM   tblTasks Ta

        ) t
WHERE Rn = 2

这将为每个ContentTypeID提供第二高的JobID记录

答案 1 :(得分:1)

我建议DENSE_RANK(),如果你想要第二个JobID

SELECT tb.*
FROM (SELECT tb.*, DENSE_RANK() OVER (ORDER BY JobID DESC) as seqnum
      FROM tblTasks Tb
     ) tb
WHERE seqnum = 2;

如果没有重复项,则OFFSET / FETCH会更容易:

SELECT tb.*
from tblTasks
ORDER BY JobId
OFFSET 1
FETCH FIRST 1 ROW ONLY;

答案 2 :(得分:0)

您可以使用以下语法:

{{1}}

答案 3 :(得分:0)

SELECT * FROM tblTasks ORDER BY col DESC LIMIT 1, 1