2015-03-30 97 views
0

我想要使用最新的CreatedDate獲取每個AccountNo的代碼,並在CurrentCode中顯示。SQL的最大分區,以獲得其他列值

|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?

回答

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