我有以下数据集。我有多天的记录。我只需要每天的最新记录。
eid aid eDate lastUpdated
8963 3493689 2018-03-29 00:00:00.000 2018-03-29 09:53:03.080
8964 3493689 2018-03-29 00:00:00.000 2018-03-30 08:44:04.087
9127 3493689 2018-04-06 00:00:00.000 2018-03-30 11:00:47.450
9008 3493689 2018-04-06 00:00:00.000 2018-03-29 11:56:51.900
所需的出站只有2条记录(eid 8964和9127)。所以基本上是一天的记录。 查询是
select eid, aid, eventdate as eDate, lastUpdated from tbl_appt where aid = '3493689'
答案 0 :(得分:4)
您可以在eDate上对数据进行分区,并获取每个分区的第一行。
如果要选择最新的记录,则需要使用order by eventdate desc
,如果要选择最旧的记录,请使用order by eventdate asc
;with ct as (
select eid, aid, eventdate as eDate, lastUpdated
, RN = ROW_NUMBER() over (PARTITION BY cast(eventdate as date) order by eventdate desc)
from tbl_appt
where aid = '3493689'
)
select eid, aid, eDate, lastUpdated
from ct
where RN = 1
答案 1 :(得分:1)
一个简单的“不存在”将起作用:
select t.eid, t.aid, t.eventdate as eDate, t.lastUpdated
from tbl_appt t
where t.aid = '3493689'
and not exists (
select 1 from tbl_appt
where aid = t.aid and eventdate = t.eventdate and lastUpdated > t.lastUpdated
)
请参见demo。
结果:
> eid | aid | eDate | lastUpdated
> ---: | ------: | :------------------ | :------------------
> 8964 | 3493689 | 2018-03-29 00:00:00.000 | 2018-03-30 08:44:04.087
> 9127 | 3493689 | 2018-04-06 00:00:00.000 | 2018-03-30 11:00:47.450
答案 2 :(得分:0)
尝试一下
;WITH CTE (eid, aid , eDate , lastUpdated)
AS
(
SELECT 8963, 3493689,'2018-03-29 00:00:00.000','2018-03-29 09:53:03.080' UNION ALL
SELECT 8964, 3493689,'2018-03-29 00:00:00.000','2018-03-30 08:44:04.087' UNION ALL
SELECT 9127, 3493689,'2018-04-06 00:00:00.000','2018-03-30 11:00:47.450' UNION ALL
SELECT 9008, 3493689,'2018-04-06 00:00:00.000','2018-03-29 11:56:51.900'
)
SELECT *
FROM
(
select eid,
aid,
eDate as eDate,
lastUpdated,
ROW_NUMBER()OVER(PARTITION BY eDate ORDER BY lastUpdated DESC) AS ltst
from CTE
)dt WHERE ltst =1
AND aid = '3493689'