1

我不是 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

任何提示?

4

2 回答 2

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))

或者:

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 |
于 2013-07-03T07:08:36.363 回答
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.我们采取相应组的最大值,以便您获得当天最新的一个

希望这可以帮助

于 2013-07-03T07:32:30.230 回答