1

我正在处理需要排序行(排序依据)和联合语句的查询。我想做的是根据时间为每个客户获取最新的读数。我知道我不能在 union 语句中使用 order by,但是有什么方法可以实现我想要的吗?我也有几个表加入了 select 语句。以下是我的示例查询:

select  top 1 name, ID, Date, Time, Cust_ID
from Table1
join Table2
on ID = Cust_ID
join Table3
on c = d
where ID = 'ID0001' 
(order by Time desc)
union all
select  top 1 name, ID, Date, Time, Cust_ID
from Table1
join Table2
on ID = Cust_ID
join Table3
on c = d
where ID = 'ID0002' 
(order by Time desc)
union all
select  top 1 name, ID, Date, Time, Cust_ID
from Table1
join Table2
on ID = Cust_ID
join Table3
on c = d
where ID = 'ID0003' 
(order by Time desc)

所以我正在寻找能够产生这些结果的东西。有人知道这种方法吗?谢谢

4

3 回答 3

3

您所要做的就是将 order by 子句放在整个查询的末尾。

select  top 1 name, ID, Date, Time, Cust_ID
from Table1
join Table2
on ID = Cust_ID
join Table3
on c = d
where ID = 'ID0001' 

union all
select  top 1 name, ID, Date, Time, Cust_ID
from Table1
join Table2
on ID = Cust_ID
join Table3
on c = d
where ID = 'ID0002' 

union all
select  top 1 name, ID, Date, Time, Cust_ID
from Table1
join Table2
on ID = Cust_ID
join Table3
on c = d
where ID = 'ID0003' 
order by ID, Time desc

编辑说明

请注意我在上述 Order by 子句中所做的更改。它将首先按 ID 升序排列,然后按客户时间降序排列。

于 2012-07-03T16:32:19.810 回答
1
select * from (
select  top 1 name, ID, Date, Time, Cust_ID from Table1
join Table2 on ID = Cust_ID
join Table3 on c = d
where ID = 'ID0001' 
union all
select  top 1 name, ID, Date, Time, Cust_ID from Table1
join Table2 on ID = Cust_ID
join Table3 on c = d
where ID = 'ID0002' 
union all
select  top 1 name, ID, Date, Time, Cust_ID from Table1
join Table2 on ID = Cust_ID
join Table3 on c = d
where ID = 'ID0003')
order by ID, Time desc
于 2012-07-03T16:24:29.430 回答
1

这似乎是一个经典问题。在 SQL Server 2005 或更高版本中,借助以下ROW_NUMBER()函数可以轻松解决:

WITH ranked AS (
  SELECT
    name, ID, Date, Time, Cust_ID,
    rnk = ROW_NUMBER() OVER (PARTITION BY ID ORDER BY Time DESC)
  FROM Table1
  JOIN Table2 ON ID = Cust_ID
  JOIN Table3 ON c = d
  WHERE ID = 'ID0001'
)
SELECT name, ID, Date, Time, Cust_ID
FROM ranked
WHERE ID IN ('ID0001', 'ID0002', 'ID0003')
  AND rnk = 1

也就是说,使用,按 的降序排列ROW_NUMBER()每组行中相同的行,然后选择排名靠前且属于特定组(即具有特定值)的行。IDTimeID

于 2012-07-03T21:08:03.973 回答