SQL:获取两个最大值

时间:2015-08-11 09:40:06

标签: sql sql-server tsql

我有以下SQLquery

SELECT r.ShopId, r.PosId , max_Temp, r.DateTime
FROM dbo.Reports r
inner join 
(Select 
rp.ShopId,
rp.PosId ,
max(T.ref.value ('TEMPERATURE[1]', 'varchar(50)')) as  max_Temp
FROM db.[dbo].[Reports] rp CROSS APPLY Snippet.nodes ('/HARDWARE_INFO/CPU_INFO/CORE') as T(ref) 
group by rp.ShopId, rp.PosId ) a
on a.ShopId = r.ShopId and a.PosId = r.PosId 
inner join 
(Select 
rp.ShopId,
rp.PosId ,
MAX(rp.DateTime) as max_date
FROM db.[dbo].[Reports] rp 
group by rp.ShopId, rp.PosId ) b
on a.ShopId = r.ShopId and a.PosId = r.PosId and b.max_date = r.DateTime 

GROUP BY r.ShopId, r.PosId, r.DateTime, a.max_Temp

我正在尝试返回PosId,ShopId,Max_Temp和max_date。 max_date是唯一一个现在不能正常工作的人。 它始终返回整个表的最大值,而不是最大温度值的最大日期。

所以基本上我想找出每个ShopId / PosId的max_temp(这将给出多个值,因为max_temp可以在不同的日期测量)具有该列表的最高日期。

1 个答案:

答案 0 :(得分:0)

你可以使用

Select * From Report
Where row_number() over (partition by PosId,ShopId Order By temp desc) = 1

或者

Select r.* From Report as r
Inner join (select PosId,ShopId, max_temp = max(temp) From report group by PosId, ShopId)  as m
on m.PosId = r.PosId and m.ShopId = r.ShopId and r.temp = m.Max_temp

使用xml可能效果不佳。 (意思是缓慢和不合理的)

select ShopId, PosId, Temp, Datetime From (
    Select 
    rp.ShopId,
    rp.PosId ,
    T.ref.value ('TEMPERATURE[1]', 'varchar(50)') as  Temp,
    row_number() over (partition by rp.ShopId, rp.PosId Order By T.ref.value ('TEMPERATURE[1]', 'varchar(50)') desc) as n
    FROM db.[dbo].[Reports] rp CROSS APPLY Snippet.nodes ('/HARDWARE_INFO/CPU_INFO/CORE') as T(ref) 
) as mx
where mx.n = 1