sql查询列出其他列(没有aggr()& groupby)

时间:2013-03-28 15:03:50

标签: sql sql-server tsql sql-server-2005

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

我的车辆表是:

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;

因此,如果没有aggregate()和group by,我可以将'address'作为第4个并获得所需的结果

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上运行,因此可以使用排名功能..

5 个答案:

答案 0 :(得分: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 Fiddle Demo

答案 1 :(得分:3)

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

如果您同时为每个rank()vehNo分配两个条目,address将返回多行。 row_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

答案 2 :(得分: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;

答案 3 :(得分: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;

答案 4 :(得分:0)

请执行以下操作:

MAX(address)

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