使用 JOINS 查找第二个最近的日期 SQL
Find 2nd Most Recent Date SQL with JOINS
我正在尝试 return SQL 中一组项目的第二个最新日期,但我收到错误 'Only one expression can be specified in the select list when the subquery is not introduced with EXISTS.'
这是我的代码:
SELECT ProjectId, max(CreatedDateTime)
FROM NTNote.dbo.nProjectReference P
INNER JOIN NTNote.dbo.nJournal J
ON J.JournalID = P.JournalID
Where CreatedDateTime < (SELECT max(CreatedDateTime), projectid
FROM NTNote.dbo.nProjectReference P
INNER JOIN NTNote.dbo.nJournal J
ON J.JournalID = P.JournalID
Group by ProjectId)
Group by ProjectId
如有任何帮助,我们将不胜感激!
您可以使用
Row_Number() over (partition by ProjectId order by CreatedDateTime desc) as rownum
并使用 2 作为谓词来获取输出。
使用以下代码获得所需的输出(sql 服务器)。
with cte_grp
as
(SELECT ProjectId,CreatedDateTime,ROW_NUMBER () OVER(PARTITION BY ProjectId ORDER BY CreatedDateTime desc) RNo
FROM NTNote.dbo.nProjectReference P
INNER JOIN NTNote.dbo.nJournal J
ON J.JournalID = P.JournalID)
SELECT *
FROM cte_grp
WHERE RNO=2
我正在尝试 return SQL 中一组项目的第二个最新日期,但我收到错误 'Only one expression can be specified in the select list when the subquery is not introduced with EXISTS.' 这是我的代码:
SELECT ProjectId, max(CreatedDateTime)
FROM NTNote.dbo.nProjectReference P
INNER JOIN NTNote.dbo.nJournal J
ON J.JournalID = P.JournalID
Where CreatedDateTime < (SELECT max(CreatedDateTime), projectid
FROM NTNote.dbo.nProjectReference P
INNER JOIN NTNote.dbo.nJournal J
ON J.JournalID = P.JournalID
Group by ProjectId)
Group by ProjectId
如有任何帮助,我们将不胜感激!
您可以使用
Row_Number() over (partition by ProjectId order by CreatedDateTime desc) as rownum
并使用 2 作为谓词来获取输出。
使用以下代码获得所需的输出(sql 服务器)。
with cte_grp
as
(SELECT ProjectId,CreatedDateTime,ROW_NUMBER () OVER(PARTITION BY ProjectId ORDER BY CreatedDateTime desc) RNo
FROM NTNote.dbo.nProjectReference P
INNER JOIN NTNote.dbo.nJournal J
ON J.JournalID = P.JournalID)
SELECT *
FROM cte_grp
WHERE RNO=2