繁体   English   中英

sql max partition by以获取其他列值

[英]sql max partition by to get other column value

我想使用最新的CreatedDate获取每个AccountNo的代码,并显示在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  |

结果将是:

|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 

如何使用SQL Server编写此SQL?

在SQL Server 2012+中,可以使用first_value()

select t.*,
       first_value(code) over (partition by AccountNo
                               order by CreatedDate desc) as MostRecentCode
from table t;

在早期版本中,我建议outer apply而不是窗口函数:

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

小提琴: http ://sqlfiddle.com/#!6/9e397/1/0

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM