sql max partition by获取其他列值

时间:2015-03-30 23:52:18

标签: sql max partition

我希望使用最新的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?

2 个答案:

答案 0 :(得分:1)

在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;

答案 1 :(得分:0)

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