most recent (max) date for every id

余生颓废 提交于 2019-12-13 07:54:42

问题


a = id  
b = date  
c = NewestDate

For every a, I have b c

How can I get the newest date for every set of id's (MY 'a' column)? they don't all have the same end date. So I do need a max for all of them.

The data is in myTable, so far i tried:

select * 
into #myTable 
from myTable

select 
t.a
,t.b
,t.c 
,(select max(b) from myTable) as c
from myTable t 
left join #myTable t1
on t.a = t1.a and t.b = t1.b
order by a, b 

The problem with the above code is that in 'c' it is placed the max date of them all, which is not what I actually want.

EDIT: the problem is now solved with the answer given by Dmitry Poliakov (thanks). Used:

SELECT a,
    b,
    max(b) OVER (PARTITION BY a) AS c
FROM myTable
ORDER BY a,b

回答1:


you can select maximum date for each group of ids as

SELECT a,
    b,
    max(b) OVER (PARTITION BY a) AS c
FROM myTable
ORDER BY a,b

EDIT: one of possible solutions for the second(edited) part of question is

WITH cte AS (
    SELECT a,
        b,
        max(b) OVER (PARTITION BY a) AS c,
        d
    FROM myTable
)
SELECT t1.a,
    t1.b,
    t1.c,
    t1.d,
    t2.d AS e
FROM cte t1
JOIN cte t2 ON t1.a=t2.a AND t1.c=t2.b



回答2:


DECLARE @updates TABLE (a int,b date,c date)
INSERT INTO @updates VALUES 
  (1,GETDATE(),GETDATE()+10), 
  (2,GETDATE()+11,GETDATE()+13),
  (2,GETDATE()+11,GETDATE()+14),
  (3,GETDATE()+11,GETDATE()+13),
  (1,GETDATE()+11,GETDATE()+13);

WITH
  cte AS
  (
    SELECT  a, max(c) latest
    FROM  @updates
    GROUP BY a
  )

SELECT  *  
FROM  cte INNER JOIN @updates as d ON cte.a=d.a AND cte.latest = d.c

Builds a table to select the records with the newest updates and then joins this new table with your original table to extract all the fields in matching rows



来源:https://stackoverflow.com/questions/32467553/most-recent-max-date-for-every-id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!