I want get Code for each AccountNo using most recent CreatedDate, and show in CurrentCode.
|ID| RoutingNo| AccountNo| Code |CreatedDate |CurrentCode
| 1| 1 | 1 | GW03 |2012-02-09 |
| 2| 1 | 1 | GW03 |2012-02-10 |
| 3| 1 | 1 | GW03 |2012-02-11 |
| 4| 1 | 1 | GW03 |2012-02-12 |
| 5| 1 | 1 | GW02 |2012-02-13 |
| 6| 1 | 2 | GW01 |2012-02-14 |
| 7| 1 | 2 | GW01 |2012-02-15 |
| 8| 1 | 2 | GW02 |2012-02-16 |
| 9| 1 | 2 | GW02 |2012-02-17 |
|10| 1 | 2 | GW01 |2012-02-18 |
The result would be:
|ID| RoutingNo| AccountNo| Code |CreatedDate |CurrentCode
| 1| 1 | 1 | GW03 |2012-02-09 |GW02
| 2| 1 | 1 | GW03 |2012-02-10 |GW02
| 3| 1 | 1 | GW03 |2012-02-11 |GW02
| 4| 1 | 1 | GW03 |2012-02-12 |GW02
| 5| 1 | 1 | GW02 |2012-02-13 |GW02
| 6| 1 | 2 | GW01 |2012-02-14 |GW01
| 7| 1 | 2 | GW01 |2012-02-15 |GW01
| 8| 1 | 2 | GW02 |2012-02-16 |GW01
| 9| 1 | 2 | GW02 |2012-02-17 |GW01
|10| 1 | 2 | GW01 |2012-02-18 |GW01
How can I write this sql using sql server?
In SQL Server 2012+, you can use first_value()
:
select t.*,
first_value(code) over (partition by AccountNo
order by CreatedDate desc) as MostRecentCode
from table t;
In earlier versions, I would recommend outer apply
instead of window functions:
select t.*, tlast.code
from table t outer apply
(select top 1 t2.code
from table t2
where t2.AccountNo = t.AccountNo
order by CreatedDate desc
) tlast;
select x.*, y.code as currentcode
from tbl x
join tbl y
on x.accountno = y.accountno
join (select accountno, max(createddate) as createddate
from tbl
group by accountno) z
on y.accountno = z.accountno
and y.createddate = z.createddate
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.