如何在SQL Server 2008中的重复ID序列中获取下一个日期

时间:2014-12-22 05:10:25

标签: sql-server date

我的表有多次出现其id和日期。例如:

     id #       date
1    abc        2014-Apr-05
2    def        2015-Mar-07
3    def        2014-Feb-02
4    abc        2013-Oct-23
5    abc        2016-Jan-10
6    xyz        2016-Jul-18
7    def        2014-Sep-03
8    xyz        2015-May-25
9    def        2013-Nov-11
10   abc        2015-Aug-16

我想知道如何滚动ID,然后浏览日期并返回每个id的最低/最早日期。如:

     id #    date
1    abc     2013-Oct-23
2    def     2013-Nov-11
3    xyz     2015-May-25

谢谢!

3 个答案:

答案 0 :(得分:1)

使用Window Function查找每个first date群组中的[id#]

SELECT [id#],
       [date]
FROM   (SELECT Row_number()
                 OVER (
                   partition BY [id#]
                   ORDER BY [date] ASC) rn,
               *
        FROM   tablename)a
WHERE  rn = 1 

FIDDLE DEMO

或使用AggregateJoin。在每个minimum date中找到Id#,在主表中找到join结果。

SELECT a.[id#],
       a.[date]
FROM   Tablename A
       JOIN (SELECT Min([date]) dates,
                    [id#]
             FROM   Tablename
             GROUP  BY [id#]) B
         ON a.[date] = b.[date]
            AND a.[id#] = b.[id#] 

答案 1 :(得分:1)

查看预期结果,可以使用简单的GROUP BYMIN日期来完成。

SELECT
    [id #]
    , MIN([date]) AS FirstDate
FROM YourTable
GROUP BY [id #]
ORDER BY [id #];

答案 2 :(得分:0)

DECLARE @t1 TABLE
  (
     id1   VARCHAR(10),
     date1 DATE
  )

INSERT INTO @t1
VALUES      ('abc',
             '2014-Apr-05'),
            ('def',
             '2015-Mar-07'),
            ('def',
             '2014-Feb-02'),
            ('abc',
             '2013-Oct-23'),
            ('abc',
             '2016-Jan-10'),
            ('xyz',
             '2016-Jul-18'),
            ('def',
             '2014-Sep-03'),
            ('xyz',
             '2015-May-25'),
            ('def',
             '2013-Nov-11'),
            ('abc',
             '2015-Aug-16')

SELECT *
FROM   (SELECT id1,
               date1,
               ROW_NUMBER()
                 OVER (
                   partition BY id1
                   ORDER BY date1) c
        FROM   @t1) t
WHERE  t.c = 1