【问题标题】:Get first date record from multiple records从多条记录中获取第一个日期记录
【发布时间】:2019-06-27 23:23:35
【问题描述】:

我有以下数据集。我有几天的多条记录。我只需要每天的最新记录。

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'

【问题讨论】:

标签: sql-server tsql


【解决方案1】:

您可以在 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

【讨论】:

    【解决方案2】:

    一个简单的不存在就可以了:

    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
    

    【讨论】:

      【解决方案3】:

      试试这个

      ;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'
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-31
        • 2020-11-10
        • 1970-01-01
        相关资源
        最近更新 更多