从组中选择前1并在查询中按顺序排序

时间:2013-06-27 18:21:07

标签: sql-server

我有一个包含以下数据的表:

ID    Field_name   change_date  prev_value  current_value

1      USER_NAME    01/01/2013     test         test11
1      USER_NAME    04/02/2013     test11       test12
2      USER_GENDER  06/01/2013     M             F
2     USER_GENDER   02/01/2013     F             M

当我按field_name分组并按change_date排序时,我会得到类似

的内容
ID    Field_name   change_date  prev_value  current_value
2      USER_GENDER  06/01/2013     M             F
2     USER_GENDER   02/01/2013     F             M 
1      USER_NAME    04/02/2013     test11       test12
1      USER_NAME    01/01/2013     test         test11

现在我需要为每个field_name选择前1行。请建议

由于

编辑:

select @cols = STUFF((SELECT distinct ',' + QUOTENAME(Field_name) 
                            from 
                            (
                                select Field_name,change_date,prev_value,current_value
                                from
                                (select *,
                                 row_number() over (partition by Field_name order by change_date desc) as 
                                ranker from tbl_User
                                )Z
                                where ranker = 1 and ID = '1' 
                            )
                    FOR XML PATH(''), TYPE
                    ).value('.', 'NVARCHAR(MAX)') 
                ,1,1,'')

预期产出:

ID     USER_GENDER  USER_NAME 
2         M            
1                     test11

1 个答案:

答案 0 :(得分:6)

窗口函数应该可以使用任何最新版本的SQL Server

select ID, Field_name,  change_date,  prev_value,  current_value
from
(select *,
 row_number() over (partition by Field_name order by change_date desc) as 
ranker from table
)Z
where ranker = 1