1

今天早些时候,我遇到了这个问题并解决了它,现在我正在修复列出一列(如果可能的话,带有排名功能)

我的车辆表是:

vehNo   tTime                     odo     address
ABC     2013-02-13 10:30:00       80       denver
ABC     2013-02-12 10:30:00       10       boston
ABC     2013-02-12 12:30:00       30       berlin
ABC     2013-02-13 01:30:00       40       montreal
ABC     2013-02-13 02:30:00       40       montreal
ABC     2013-02-13 03:30:00       40       montreal

XYZ     2013-02-13 03:33:00       44       houston
ABC     2013-02-13 04:30:00       60       madrid
ABC     2013-02-13 11:30:00       100      alaska

目前以下查询工作正常(在两次之间列出 3 列)

select vehNo, max(tTime) as [tTime], odo
from Table_3
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;

因此,如果没有聚合()和分组依据,我可以将“地址”作为第四个并获得所需的结果

vehNo   tTime                     odo     address
ABC     2013-02-12 10:30:00       10     boston
ABC     2013-02-12 12:30:00       30     berlin
ABC     2013-02-13 03:30:00       40     montreal(time latest, ignoring 1:30 & 2:30)
ABC     2013-02-13 04:30:00       60     madrid
ABC     2013-02-13 10:30:00       80     denver

我在 SQL Server 2005 上运行,所以可以有排名功能..

4

5 回答 5

4

试试这个:

WITH CTE
AS
(
   SELECT *,
     ROW_NUMBER() OVER(PARTITION BY vehNo, odo
                       ORDER BY tTime DESC) AS RowNum 
   FROM table_3
   where vehNo = 'ABC' 
     and tTime between '2013-02-12 10:30:00' 
                   and '2013-02-13 10:30:00'
)
SELECT *
FROM CTE
WHERE RowNum = 1;

SQL 小提琴演示

于 2013-03-28T15:06:47.800 回答
3

您可以使用窗口/排名函数来获得结果。我可以看到两个选项row_number()rank()。使用窗口函数时,您可以使用WHERE子句仅返回排名为 1 的行。

如果您同时rank()有两个条目,则将返回多行。将只返回第一行。因此,您需要决定哪种功能最适合您的情况:vehNoaddressrow_number()

select vehNo, tTime, odo, address
from 
(
  select vehNo, tTime, odo, address,
    rank() over(partition by vehNo, odo order by tTime desc) rnk
  from yourtable
  where vehNo = 'ABC' 
    and tTime between '2013-02-12 10:30:00' and '2013-02-13 10:30:00'
) d
where rnk = 1

请参阅SQL Fiddle with Demo

于 2013-03-28T15:08:57.153 回答
1

使用 CTE:

WITH ag 
(
    select vehNo, max(tTime) as [tTime], odo
    from Table_3
    where vehNo = 'ABC' 
      and tTime between '2013-02-12 10:30:00' 
                    and '2013-02-13 10:30:00'
    group by vehNo, odo
)
select vehNO, tTime, odo, T.address
from ag 
inner join ag on Table_3 T on ag.vehNo=T.vehNo
order by vehNo, odo;
于 2013-03-28T15:08:30.227 回答
0

您是否尝试过使用该row_number()功能?

select 
row_number() OVER (ORDER BY vehNo) AS period,
vehNo, max(tTime) as [tTime], odo
from Table_3
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-28T15:08:27.620 回答
0

只需执行以下操作:

MAX(address)

即使它是 varchar,您仍然可以使用 MAX。

于 2013-03-28T15:10:25.790 回答