获取每一天的最新时间?

时间:2013-07-03 07:02:14

标签: sql-server-2008

我不是一个大SQL的人,所以我希望这个问题不是太愚蠢,但我还没有找到答案。

我有一张看起来像这样的表:

LastUpdate                       |  TheValue
-------------------------------------------------
2013-06-25 06:44:18.530          |  1
2013-06-25 06:59:18.500          |  7
2013-06-25 12:51:18.530          |  3
2013-06-26 07:44:18.530          |  5
2013-06-26 09:44:18.530          |  9
2013-06-28 08:44:18.530          |  0
2013-06-28 11:44:18.530          |  1

因此,我希望每天的最后一个条目具有值:

LastUpdate                       |  TheValue
-------------------------------------------------
2013-06-25 12:51:18.530          |  3
2013-06-26 09:44:18.530          |  9
2013-06-28 11:44:18.530          |  1

任何提示?

2 个答案:

答案 0 :(得分:4)

查询:

SELECT t1.*
FROM Table1 t1
WHERE t1.LastUpdate = (SELECT MAX(t2.LastUpdate) 
                       FROM Table1 t2
                       WHERE CAST(t1.LastUpdate AS DATE) = 
                             CAST(t2.LastUpdate AS DATE))

OR:

SELECT a.*
FROM(SELECT t1.*,
     ROW_NUMBER() OVER(PARTITION BY CAST(t1.LastUpdate  AS DATE)  ORDER BY t1.LastUpdate DESC)  tt
     FROM Table1 t1)a 
WHERE a.tt = 1

结果:

|                  LASTUPDATE | THEVALUE |
------------------------------------------
| June, 25 2013 12:51:18+0000 |        3 |
| June, 26 2013 09:44:18+0000 |        9 |
| June, 28 2013 11:44:18+0000 |        1 |

答案 1 :(得分:2)

试试这个

WITH TEMP as
(
  SELECT MAX(LastUpdate) as TempLastUpdate
  FROM yourTable Group by CONVERT(VARCHAR(10),LastUpdate,111) 
)

SELECT LastUpdate,TheValue from yourTable WHERE LastUpdate IN (SELECT TempLastUpdate  FROM Temp)

结果

LastUpdate                       |  TheValue
-------------------------------------------------
2013-06-25 12:51:18.530          |  3
2013-06-26 09:44:18.530          |  9
2013-06-28 11:44:18.530          |  1

说明: -

1.我们首先按日期分组,没有时间

2.我们取得相应组的最大值,以便您获得当天最新的一个

希望这有帮助