如何指定前N行匹配条件?

时间:2012-02-27 22:04:41

标签: dataset sql-server-2008

我正在使用SSMS 2008,我创建了一个带有sproc的数据集,该sproc返回许多记录。但是,有一个日期列可以在此数据集中具有相同的值。现在我想要做的是过滤这些记录以仅包含来自该数据集的最新数据。我如何在T-SQL中执行此操作? (我只想看下面的2/5记录。)

例如:

col A     col B     col C
AAAAAA    BBBBBB    2/5/2012
AAAAA2    BBBBB2    2/5/2012
AAAAA3    BBBBB3    2/1/2012
AAAAA4    BBBBB4    1/25/2012
AAAAA5    BBBBB5    1/25/2012
AAAAA6    BBBBB6    1/10/2012

我尝试了你的solutoin Andreas,但我现在收到了错误:

  

Msg 102,Level 15,State 1,Line 74')'附近的语法不正确。

以下是代码段:

select *
from (
    select *, row_number() over(partition by [test_details_answers_expanded_view].[actual_date] 
    order by [test_details_answers_expanded_view].[actual_date] desc) rowno
    from 
    (
Select
    [test_details_answers_expanded_view].[event_log_id],
...
[test_details_answers_expanded_view].[actual_date],
...
FROM #TEMP_EVENT_LOG A  
JOIN [evolv_reports].[dbo].[test_header_rv] ON A.[event_log_id] = [test_header_rv].[event_log_id]
CROSS APPLY [dbo].[fn_getTestSetupFormDetails](null, [test_header_rv].[test_setup_header_id]) AS [test_header]
CROSS APPLY [dbo].[fn_getTestSetupFormDetails]([test_header].[test_setup_details_id], null) AS [test_details]
JOIN [evolv_reports].[dbo].[test_details_answers_expanded_view] ON
        [test_header_rv].[test_header_id] = [test_details_answers_expanded_view].[test_header_id]
    AND [test_details].[test_setup_details_id] = [test_details_answers_expanded_view].[test_setup_details_id]
Where  
(@TestHeaderCode Is Null OR [test_header].[test_header_code] = @TestHeaderCode)
   AND (@TestHeaderID Is Null OR [test_header_rv].[test_header_id] = @TestHeaderID)
) t
where rowno = 1

你能告诉我这里做错了吗?

1 个答案:

答案 0 :(得分:0)

以下是使用row_number的示例:

select *
from (
    select *, row_number() over(partition by [col c] order by [col c] desc) rowno
    from table
) t
where rowno = 1