SQL按日期获取上次记录

时间:2014-02-18 09:49:09

标签: sql

我有一张这样的表:

InstallID   |InstallationDate
1           |01-01-2014
1           |01-02-2014
1           |01-03-2014
1           |01-04-2014
2           |01-01-2014
2           |01-02-2014
3           |01-01-2014
3           |01-02-2014
3           |01-03-2014
4           |01-04-2014
4           |01-05-2014

我需要为每个安装ID获取最新的installationDate

e.g。

InstallID   |InstallationDate
1           |01-04-2014
2           |01-02-2014
3           |01-03-2014
4           |01-05-2014

有人可以帮助我如何使用SQL实现上述目标吗?

7 个答案:

答案 0 :(得分:1)

查询:

<强> SQLFiddleExample

SELECT t1.InstallID, 
       t1.InstallationDate
FROM yourTable t1
 LEFT JOIN yourTable t2
  ON t1.InstallID = t2.InstallID
  AND t1.InstallationDate < t2.InstallationDate
WHERE t2.InstallID is null

结果:

| INSTALLID |               INSTALLATIONDATE |
|-----------|--------------------------------|
|         1 | January, 04 2014 00:00:00+0000 |
|         2 | January, 02 2014 00:00:00+0000 |
|         3 | January, 03 2014 00:00:00+0000 |
|         4 | January, 05 2014 00:00:00+0000 |

答案 1 :(得分:0)

请尝试:

SELECT
    InstallID,
    MAX(InstallationDate)
FROM
    YourTable
GROUP BY InstallID

答案 2 :(得分:0)

试试这个

Group By

SELECT InstallID,MAX(InstallationDate)
FROM TABLE1
GROUP BY InstallID

<强>(或)

Row_Number

SELECT InstallID,InstallationDate FROM
(
SELECT InstallID,InstallationDate,
       ROW_NUMBER() OVER (PARTITION BY InstallID,InstallationDate ORDER BY InstallID) AS RN,
       COUNT(*) over (PARTITION BY InstallID,InstallationDate) as CN
FROM Table1 
) AS T WHERE RN = CN

答案 3 :(得分:0)

Select InstallID   , MAX(InstallationDate)
From yourTable
Group  By InstallID

答案 4 :(得分:0)

试试这个,

SELECT installid,
       MAX(installationdate)
FROM <table_name>
GROUP BY installid

答案 5 :(得分:0)

试试这个

SELECT InstallID, MAX(InstallationDate)
FROM <TableName>
GROUP BY InstallID

答案 6 :(得分:0)

我认为最简单的方法是

SELECT t1.InstallID, 
   MAX(t1.InstallationDate)
FROM yourTable t1
Group by t1.InstallID