如何使用内部联接来摆脱我不想要的欺骗? 我正在研究的表格如下:
ID Edited_date Status
------------------------
1 1/1/2015 A
1 1/1/2016 B
1 2/1/2016 C
2 1/1/2017 D
2 3/1/2017 B
3 1/1/2016 C
3 4/1/2017 B
3 1/1/2014 D
但是,我只想从最近的edited_date
获得每笔贷款的状态ID Edited_date Status
------------------------
1 2/1/2016 C
2 3/1/2017 B
3 4/1/2017 B
答案 0 :(得分:2)
select * from [table] t1
inner join
(
select ID, max(Edited_date) maxDt
from [Table]
group by ID
) t2
on t1.ID = t2.ID
and t1.Edited_date = t2.maxDt;
答案 1 :(得分:1)
仅供选择:
SELECT *
FROM
(
SELECT *, ROW_NUMBER()OVER(PARTITION BY ID ORDER BY Edited_date desc) as Indicator
FROM TABLE_NAME
) as ABC
WHERE ABC.Indicator = 1
删除:
WITH ABC
AS
(
SELECT *, ROW_NUMBER()OVER(PARTITION BY ID ORDER BY Edited_date desc) as Indicator
FROM TABLE_NAME
)
DELETE FROM ABC
WHERE ABC.Indicator != 1
答案 2 :(得分:1)
使用id
分区的row_number()
获取最新的edited_date
select id, edited_date, status
from (
select *
, rn = row_number() over (partition by id order by edited_date desc)
from t
) as s
where rn = 1
select top 1 with ties
id
, edited_date
, status
from t
order by row_number() over (partition by id order by edited_date desc)
答案 3 :(得分:-1)
Begin Transaction
Create table #temp (Id int, Edited_date date, Status char(2))
Insert into #temp
Values
('1','1/1/2015','A'),
('1','1/1/2016','B'),
('1','2/1/2016','C'),
('2','1/1/2017','D'),
('2','3/1/2017','B'),
('3','1/1/2016','C'),
('3','4/1/2017','B'),
('3','1/1/2014','D')
Create table #temp2 (Id int, Edited_date date, Status char(2))
Insert into #temp2
Values
('1','2/1/2016','C'),
('2','3/1/2017','B'),
('3','4/1/2017','B')
/** emphasis on the below **/
;with cte as (
Select max(Edited_date) as Edited_date, Status From #temp Group By Status
union all
Select max(Edited_date) as Edited_date, Status From #temp2 Group By Status
)
Select Status, max(Edited_date) as Recent_Edited_date From cte Group By Status
/** End of Emphasis **/
Drop table #temp
Drop table #temp2
Rollback
--- Result ---
Status| Recent_Edited_date
A| 2015-01-01
B| 2017-04-01
C| 2016-02-01
D| 2017-01-01