我正在尝试获取ID的修改日期早于7天的最新记录,但是,结果将返回ID早于7天的记录的所有记录。
SELECT USERID
FROM [PROJ]
INNER JOIN [NOTES] ON [PROJ].id = [NOTES].projID
WHERE [PROJ.STATUS] = 'ACTIVE'
AND [NOTES.MODIFIEDDATE] <= GETDATE() - 7
返回:
project userId modifieddate
1. 20190101 6 07/02/2019 *
2. 20190101 6 07/01/2019
3. 20190101 6 06/29/2019
4. 20190102 7 07/04/2019 *
5. 20190102 7 07/03/2019
*是我期望返回的结果。 这将返回所有ID注释的修改日期小于7天的所有记录,我只希望最近的注释(修改日期)早于7天。
答案 0 :(得分:0)
尝试添加一个hading子句
SELECT USERID
FROM [PROJ]
INNER JOIN [NOTES] ON [PROJ].id = [NOTES].projID
WHERE [PROJ.STATUS] = 'ACTIVE'
AND [NOTES.MODIFIEDDATE] <= GETDATE() - 7
GROUP BY USERID
HAVING MAX([NOTES.MODIFIEDDATE])
编辑: 如果您只想要最新的,那我将完全摆脱
AND [NOTES.MODIFIEDDATE] <= GETDATE() - 7
SELECT USERID
FROM [PROJ]
INNER JOIN [NOTES] ON [PROJ].id = [NOTES].projID
WHERE [PROJ.STATUS] = 'ACTIVE'
GROUP BY USERID
HAVING MAX([NOTES.MODIFIEDDATE])
EDIT2:
SELECT USERID
FROM [PROJ]
INNER JOIN [NOTES] ON [PROJ].id = [NOTES].projID
WHERE [PROJ.STATUS] = 'ACTIVE'
AND [NOTES.MODIFIEDDATE] <= GETDATE() - 7
GROUP BY USERID, PROJECT
HAVING MAX([NOTES.MODIFIEDDATE])