3

我的汽车桌子看起来像

vehNo   tTime                     odo     
ABC     2013-02-13 10:30:00       80       
ABC     2013-02-12 10:30:00       10      
ABC     2013-02-12 12:30:00       30      
ABC     2013-02-13 01:30:00       40      
ABC     2013-02-13 02:30:00       40 
ABC     2013-02-13 03:30:00       40 
XYZ     2013-02-13 03:33:00       44
ABC     2013-02-13 04:30:00       60 
ABC     2013-02-13 11:30:00       100 

我可以在 2013 年 2 月 12 日 10:30:00 到 2013 年 2 月 13 日 10:30:00 之间给出(按时间排序),但我如何获得 DISTINCT odo like

ABC     2013-02-12 10:30:00       10 
ABC     2013-02-12 12:30:00       30 
ABC     2013-02-13 03:30:00       40         (time being latest, ignoring 1:30 & 2:30)
ABC     2013-02-13 04:30:00       60
ABC     2013-02-13 10:30:00       80 

我在 MSSql 服务器 2005 上运行

4

6 回答 6

2
select vehNo, max(tTime) as [tTime], odo
from vehicles
group by vehNo, odo
order by vehNo, odo

显然,对于“2013-02-12 10:30:00 和 2013-02-13 10:30:00”之间,您可以where在中间添加一个子句:

select vehNo, max(tTime) as [tTime], odo
from vehicles
where tTime between @start and @end
group by vehNo, odo
order by vehNo, odo
于 2013-03-28T11:47:10.273 回答
1

SQL Server 2005 已经支持Common Table ExpressionWindow Function. 在它的帮助下ROW_NUMBER(),通过指定记录的顺序对组中的记录进行排序。

WITH latestDate
AS
(
    SELECT vehNo, tTime, odo,
            ROW_NUMBER() OVER (PARTITION BY vehNo, odo
                                ORDER BY tTime DESC) rn
    FROM    tableName
)
SELECT  vehNo, tTime, odo
FROM    latestDate
WHERE   rn = 1
于 2013-03-28T11:46:10.007 回答
1

试试这样;

select vehNo, max(tTime) as tTime, odo
from myTable
group by vehNo, odo
order by vehNo, odo

| VEHNO |               TTIME | ODO |
-------------------------------------
|   ABC | 2013-02-12 10:30:00 |  10 |
|   ABC | 2013-02-12 12:30:00 |  30 |
|   ABC | 2013-02-13 03:30:00 |  40 |
|   ABC | 2013-02-13 04:30:00 |  60 |
|   ABC | 2013-02-13 10:30:00 |  80 |
|   ABC | 2013-02-13 11:30:00 | 100 |

这里是SQL Fiddle DEMO

于 2013-03-28T11:50:20.303 回答
1

好的@mark我将我的解决方案扩展为

select vehNo, max(tTime) as [tTime], odo
from Table_1
where vehNo = 'ABC' and tTime between '2013-02-12 10:30:00' and '2013-02-13 10:30:00'
group by vehNo, odo
order by vehNo, odo
于 2013-03-28T12:05:07.890 回答
0

我想你可能想要 GROUP BY odo 并选择 MAX(tTime)。听起来对吗?

于 2013-03-28T11:46:07.720 回答
0
SELECT
  vehNO, 
  MAX(tTime) AS tTime,
  MAX(odo) AS odo
FROM vehicle
WHERE ...
GROUP BY ...
于 2013-03-28T11:46:32.653 回答