我正在尝试在SQL Server 2008中选择具有第二个最新日期的行。我想为每个ID提取第二个最新日期。
+----+-----------+
|ID |Date |
+----+-----------+
|01 |2017-01-01 |
|01 |2016-04-25 |
|01 |2015-01-25 |
|02 |2017-02-01 |
|02 |2016-03-15 |
|02 |2015-09-24 |
|03 |2017-02-12 |
|03 |2016-03-05 |
|03 |2015-01-02 |
+----+-----------+
所以我想最终:
+---+-----------+
|01 |2016-04-25 |
|02 |2016-03-15 |
|03 |2016-03-05 |
+---+-----------+
我已经想出如何拉出maxdate而不是第二个最新日期。任何帮助是极大的赞赏。这个论坛对像我这样的新手很有帮助!
答案 0 :(得分:1)
你可以用这个:
SELECT id, date
FROM
(
SELECT id, date,
ROW_NUMBER() OVER (PARTITION BY id ORDER BY date DESC) rn
FROM table_name
) t
WHERE rn = 2;
如果您有多行包含第二个最新日期,则应考虑将ROW_NUMBER()
更改为RANK()
答案 1 :(得分:0)
SELECT MAX(日期)来自员工WHERE日期< (SELECT Max(date)FROM table);
或
SELECT MAX(date)FROM Employee WHERE date NOT IN(SELECT Max(date)FROM table);
了解详情:http://www.java67.com/2015/01/second-highest-salary-in-mysql-and-sql-server.html#ixzz4ZUWYpZ1p
答案 2 :(得分:0)
试试这个:
Create table SampleTable(ID INT ,Dates Date)
insert into SampleTable values(01 ,'2017-01-01')
insert into SampleTable values(01 ,'2016-04-25')
insert into SampleTable values (01 ,'2015-01-25')
insert into SampleTable values(02 ,'2017-02-01')
insert into SampleTable values(02 ,'2016-03-15')
insert into SampleTable values (02 ,'2015-09-24')
insert into SampleTable values (03 ,'2017-02-12')
insert into SampleTable values (03 ,'2016-03-05' )
insert into SampleTable values (03 ,'2015-01-02')
select id, dates from (select id,dates,row_number() over (partition by id order by id desc )rowno from SampleTable)x where x.rowno=2