选择日期和时间列的最后一条记录
Posted
技术标签:
【中文标题】选择日期和时间列的最后一条记录【英文标题】:Select the last record for the date and time columns 【发布时间】:2017-02-13 14:47:52 【问题描述】:我需要选择学术表中的最后一条记录,它有两列日期和时间。当我运行查询时,我得到一个错误。当子查询不使用 EXISTS 引入时,选择列表中只能指定一个表达式。
USE PCUnitTest
SELECT C.ACCOUNTNO, C.CONTACT, C.LASTNAME, C.KEY4, A.PEOPLE_ID, A.APP_STATUS, A.APP_DECISION, A.REVISION_DATE, A.REVISION_TIME
FROM ACADEMIC AS A INNER JOIN
GM.dbo.CONTACT1 AS C ON A.PEOPLE_ID = C.KEY4
WHERE A.REVISION_DATE = (SELECT TOP (1) REVISION_DATE, REVISION_TIME, PEOPLE_CODE, PEOPLE_ID, PEOPLE_CODE_ID, ACADEMIC_YEAR, ACADEMIC_TERM, ACADEMIC_SESSION, PROGRAM, DEGREE, CURRICULUM
FROM PCUnitTest.dbo.ACADEMIC
ORDER BY REVISION_DATE DESC, REVISION_TIME DESC)
【问题讨论】:
SELECT TOP (1) REVISION_DATE, REVISION_TIME,...
选择多个您要分配给A.REVISION_DATE
的列。这对你有意义吗?
是的,但时间和日期在不同的列中,时间取决于日期。会是日期 = 某物,时间 = 某物吗?
该学术表有 7 个键,我需要选择最后一条记录并在 REVISION_DATE、REVISION_TIME 之前更新 PEOPLE_ID 的状态列。该学术表有 7 个键 PEOPLE_CODE_ID、ACADEMIC_YEAR、ACADEMIC_TERM、ACADEMIC_SESSION、PROGRAM、DEGREE、CURRICULUM
谢谢,是的,如果我只有一个 revision_date 列,则查询完成,但时间取决于日期,我是否只需添加另一个和 where 修订时间子查询。
然后我有,WHERE A.REVISION_DATE = (SELECT TOP (1) REVISION_DATE FROM PowerCampusUnitTest.dbo.ACADEMIC ORDER BY REVISION_DATE DESC, REVISION_TIME DESC) AND A.REVISION_TIME = (SELECT TOP (1) REVISION_TIME FROM PowerCampusUnitTest.dbo.ACADEMIC ORDER BY REVISION_DATE DESC, REVISION_TIME DESC) 我将用一些数据对其进行测试,看看它是否返回正确的行。
【参考方案1】:
您可以在 where 中加入您正在使用的查询
USE PowerCampusUnitTest
SELECT C.ACCOUNTNO, C.CONTACT, C.LASTNAME, C.KEY4, A.PEOPLE_ID, A.APP_STATUS, A.APP_DECISION, A.REVISION_DATE, A.REVISION_TIME
FROM ACADEMIC AS A
INNER JOIN GoldMineUnitTest.dbo.CONTACT1 AS C
ON A.PEOPLE_ID = C.KEY4
INNER JOIN (
SELECT TOP 1 A2.REVISION_DATE,A2.REVISION_TIME FROM PowerCampusUnitTest.dbo.ACADEMIC A2
ORDER BY REVISION_DATE DESC, REVISION_TIME DESC
)AS A2
ON A.REVISION_DATE = A2.REVISION_DATE AND A.REVISION_TIME = A2.REVISION_TIME
【讨论】:
【参考方案2】:使用 ROW_NUMBER()
USE PCUnitTest
SELECT
R.ACCOUNTNO, R.CONTACT, R.LASTNAME, R.KEY4, R.PEOPLE_ID, R.APP_STATUS, R.APP_DECISION, R.REVISION_DATE, R.REVISION_TIME
FROM
(
SELECT C.ACCOUNTNO, C.CONTACT, C.LASTNAME, C.KEY4, A.PEOPLE_ID, A.APP_STATUS, A.APP_DECISION, A.REVISION_DATE, A.REVISION_TIME
,ROW_NUMBER() OVER (ORDER BY A.REVISION_DATE DESC, A.REVISION_TIME DESC) RN
FROM ACADEMIC AS A INNER JOIN
GMUnitTest.dbo.CONTACT1 AS C ON A.PEOPLE_ID = C.KEY4
) R
WHERE RN=1
如果要获取每个 PEOPLE_ID 的最新行,则添加 PARTITION BY
SELECT
R.ACCOUNTNO, R.CONTACT, R.LASTNAME, R.KEY4, R.PEOPLE_ID, R.APP_STATUS, R.APP_DECISION, R.REVISION_DATE, R.REVISION_TIME
FROM
(
SELECT C.ACCOUNTNO, C.CONTACT, C.LASTNAME, C.KEY4, A.PEOPLE_ID, A.APP_STATUS, A.APP_DECISION, A.REVISION_DATE, A.REVISION_TIME
,ROW_NUMBER() OVER (PARTITION BY A.PEOPLE_ID ORDER BY A.REVISION_DATE DESC, A.REVISION_TIME DESC) RN
FROM ACADEMIC AS A INNER JOIN
GMUnitTest.dbo.CONTACT1 AS C ON A.PEOPLE_ID = C.KEY4
) R
WHERE RN=1
【讨论】:
以上是关于选择日期和时间列的最后一条记录的主要内容,如果未能解决你的问题,请参考以下文章