我正试图获得两组之间最后到达的值。这是我正在开发的代码
USE KronosNET22
GO
Select distinct
dbo.[Object].Name, dbo.[ObjectSignal_2016_07_22].Code,
MAX(dbo.[ObjectSignal_2016_07_22].TimeIn) as tiempo
from
dbo.[Object],dbo.[ObjectSignal_2016_07_22]
where
dbo.[Object].IdClient = '6C74F97C-7253-415D-96B1-4B902D8334D7'
and (dbo.[ObjectSignal_2016_07_22].Code = 'ON3' or
dbo.[ObjectSignal_2016_07_22].Code = 'OFF3' or
dbo. [ObjectSignal_2016_07_22].Code = 'E401' or
dbo.[ObjectSignal_2016_07_22].Code = 'R401')
and dbo.[Object].Name = dbo.[ObjectSignal_2016_07_22].ObjectName
group by
dbo.[Object].Name, dbo.[ObjectSignal_2016_07_22].Code
order by
dbo.[Object].Name, MAX(dbo.[ObjectSignal_2016_07_22].TimeIn) desc
这是我得到的结果
AV CHILE PORCIUNCULA ON3 1469211062
AV CHILE PORCIUNCULA OFF3 1469195866
CALIMA ON3 1469230879
CALIMA OFF3 1469217492
CAMPANARIO POPAYAN ON3 1469210662
CAMPANARIO POPAYAN OFF3 1469203155
EL PROGRESO -- DOS QUEBRADAS OFF3 1469194694
EL PROGRESO -- DOS QUEBRADAS ON3 1469146950
EXITO -- SUBA ON3 1469214392
EXITO -- SUBA OFF3 1469199388
MEGACITY ZIPAQUIRA OFF3 1469194774
MERCURIO ON3 1469231767
MERCURIO OFF3 1469198081
METROPOLITANO ON3 1469228672
METROPOLITANO OFF3 1469225061
NIZA OFF3 1469218151
NIZA ON3 1469214985
PLATINO ON3 1469228261
PLATINO OFF3 1469217680
PORTAL DEL PRADO OFF3 1469147653
TITAN PLAZA OFF3 1469213346
TITAN PLAZA ON3 1469211705
我怎样才能使它只出现更高的值,所以我没有得到同一个地方的两个值。
答案 0 :(得分:0)
你真的应该开始使用ANSI-92样式连接。它们已经存在了20多年。那些逗号分隔的表名是一个坏习惯。
在同一查询中使用distinct和group by没有意义。
您还应该使用别名来使您的查询更加清晰。至于你的实际问题,你可以使用ROW_NUMBER。这样的事情应该非常接近。
with MySortedResults as
(
Select
o.Name
, os.Code
, os.TimeIn as tiempo
, ROW_NUMBER() over (partition by o.Name order by os.TimeIn desc) as RowNum
from dbo.[Object] o
join dbo.[ObjectSignal_2016_07_22] os on o.Name = os.ObjectName
where
o.IdClient = '6C74F97C-7253-415D-96B1-4B902D8334D7'
and os.Code IN ('ON3', 'OFF3', 'E401', 'R401')
)
select sr.Name
, sr.Code
, sr.tiempo
from MySortedResults sr
where sr.RowNum = 1
order by sr.Name