如何按ID和最早的开始日期获取不同的行?

时间:2015-07-08 17:56:28

标签: sql sql-server

如何按行ID对行进行分组,只选择开始日期排序的最早开始日期asc - group by和order by?

示例数据:

id;start_date;description;status;web_enabled;decision
31147020;2014-05-24 00:00:00.000;Description 1;Planning;1; 
31147020;2014-06-14 00:00:00.000;Description 1;Planning;1; 
31147023;2014-04-05 00:00:00.000;Description 2;Planning;1; 
31147023;2014-05-09 00:00:00.000;Description 2;Planning;1; 
31147023;2014-05-10 00:00:00.000;Description 2;Planning;1; 
31147023;2014-05-17 00:00:00.000;Description 2;Planning;1; 
31147101;2013-02-11 00:00:00.000;Description 3;Planning;1; 
31147101;2013-02-13 00:00:00.000;Description 3;Planning;1; 
31147101;2013-02-17 00:00:00.000;Description 3;Planning;1; 
31147101;2013-02-18 00:00:00.000;Description 3;Planning;1; 
31147101;2013-02-20 00:00:00.000;Description 3;Planning;1; 
31147101;2015-02-21 00:00:00.000;Description 3;Registration;1; 
31147108;2014-04-01 00:00:00.000;Description 4;Registration;1; 
31147108;2014-05-16 00:00:00.000;Description 4;Registration;1; 
31147113;2014-02-19 00:00:00.000;Description 5;Registration;1; 
31147113;2014-02-25 00:00:00.000;Description 5;Registration;1; 
31147113;2014-02-27 00:00:00.000;Description 5;Registration;1; 
31147113;2014-05-14 00:00:00.000;Description 5;Registration;1; 
31147113;2014-05-22 00:00:00.000;Description 5;Registration;1; 
31147113;2014-05-27 00:00:00.000;Description 5;Registration;1; 
31147113;2014-08-27 00:00:00.000;Description 5;Registration;1; 
31147113;2014-09-04 00:00:00.000;Description 5;Registration;1; 
31147113;2014-09-09 00:00:00.000;Description 5;Registration;1; 
31147113;2014-11-19 00:00:00.000;Description 5;Registration;1; 

期望的结果:

31147020;2014-05-24 00:00:00.000;Description 1;Planning;1; 
31147023;2014-04-05 00:00:00.000;Description 2;Planning;1; 
31147101;2013-02-11 00:00:00.000;Description 3;Planning;1; 
31147108;2014-04-01 00:00:00.000;Description 4;Registration;1; 
31147113;2014-02-19 00:00:00.000;Description 5;Registration;1; 

1 个答案:

答案 0 :(得分:2)

您可以使用ROW_NUMBER来标识第一个元素。您将按id进行分区,然后按start_date排序,以便由最早的start_date确定的每个id的第一次出现将具有1,因此在外部查询中您可以过滤以仅显示ROW_NUMBER为1的位置

SELECT *
FROM (
    SELECT *,
        ROW_NUMBER() OVER (PARTITION BY id ORDER BY start_date) AS RowNum
    FROM [SourceTable]
    ) T
WHERE RowNum = 1