SQL-如何仅获取每个ID的上一个日期的最新和最新

时间:2019-05-23 12:06:32

标签: sql snowflake-datawarehouse

我有一张桌子:

id, date, value
a,  5/22/2019 11:00, 2211
b,  5/22/2019 11:00, 2211
c,  5/22/2019 11:00, 2211
a,  5/22/2019 10:00, 2210
b,  5/22/2019 10:00, 2210
c,  5/22/2019 10:00, 2210
a,  5/21/2019 17:00, 2117
b,  5/21/2019 17:00, 2117
c,  5/21/2019 17:00, 2117
a,  5/21/2019 15:00, 2115
b,  5/21/2019 15:00, 2115
c,  5/21/2019 15:00, 2115

想要获取ID(ID)和当前(最新)值以及前一个日期的最新值:

id, latest, previous_date_close
a,   2211,    2117
b,   2211,    2117
c,   2211,    2117

到目前为止,我的某些部分(当前行和上一行)有效,但是需要上一个日期的最新和最新消息:

with cte as
(
select 
    id, value,
    lag(value, 1, 0) over (partition by id order by date ) as "date - 1",
    row_number() over(partition by id order by date desc) rn
from 
    table1
) select * from cte where rn=1

谢谢。

2 个答案:

答案 0 :(得分:1)

嗯。 。 。我认为有两个级别的窗口函数可以满足您的需求:

with cte as (
      select id, value,
             lag(value, 1, 0) over (partition by id order by date ) as "date - 1",
             row_number() over (partition by id order by date desc) as rn
      from (select t1.*,
                   row_number() over (partition by id, to_date(date) order by date desc) as seqnum_id_day
            from table1 t1
           ) t1
     where seqnum_id_day = 1
    )
select *
from cte
where rn = 1;

答案 1 :(得分:0)

您可以使用两个CTE。

WITH myCte AS (
SELECT 
    id, 
    value,
    row_number() over(PARTITION BY id ORDER BY date DESC) rn
FROM 
    table1
),

myOtherCte AS (
SELECT
    a.id,
    a.svalue,
    row_number() over(PARTITION BY a.id ORDER BY a.date DESC) rn
FROM
    table1 a
WHERE
    CAST(a.date AS DATE) < (SELECT MAX(CAST(b.date AS DATE))
                                                   FROM table1 b
                                                   WHERE a.id = b.id)
)   

SELECT
  t1.id,
  t1.value,
  t2.value
FROM myCte t1
JOIN myOtherCte t2 ON t1.id = t2.id
WHERE t1.rn = 1
AND t2.rn = 1

以下是此操作的演示:SQL Fiddle