我是SQL新手,我遇到的问题是我在表中有很多资产的价值。 我需要为该表中的每个资产获得最高速度。
我试过搜索谷歌但我找到了SQL的MAX()
函数。
我不需要MAX()
,因为这只会给我一条具有最高价值的记录。我需要每个资产的最高价:
e.g。
iAssetId fSpeedKPH
1 78
5 77
5 80
8 74
8 81
8 88
8 111
24 71
24 78
24 79
24 79
24 82
24 84
24 90
24 91
24 92
我突出显示了每个资产的最高行,即AssetId = 1,5,24和8
这些是我需要选择的行。
最有效的方法是什么?
我是否必须遍历我编写的SQL返回的结果集?
修改
我的SQL:
DECLARE @dateMinusDay datetime = DateAdd(dd, -1, GetDate())
select vm.iAssetId, max(vm.fSpeedKPH), vm.dtUTCDateTime, ge.sGeofenceName from VehicleMonitoringLog vm
inner join Geofences ge on ge.iGeofenceId = vm.iGeofenceId
where vm.iGeofenceId != 1 AND vm.fSpeedKPH > 70 AND (vm.dtUTCDateTime > @dateMinusDay AND vm.dtUTCDateTime < GETDATE())
group by
vm.iAssetId,vm.fSpeedKPH, vm.dtUTCDateTime, ge.sGeofenceName
答案 0 :(得分:5)
select iAssetId, max(fSpeedKPH)
from AssetsTable
group by iAssetId
答案 1 :(得分:1)
SELECT iAssetId, fSpeedKPH
FROM (
SELECT iAssetId, fSpeedKPH
,ROW_NUMBER() OVER (PARTITION BY iAssetId ORDER BY fSpeedKPH DESC) AS RN
FROM Table_Name )Sub
WHERE RN = 1
<强>更新强>
DECLARE @dateMinusDay datetime = DateAdd(dd, -1, GetDate())
SELECT Q.iAssetId, Q.dtUTCDateTime, Q.sGeofenceName
FROM (
select vm.iAssetId
, vm.dtUTCDateTime
, ge.sGeofenceName
,ROW_NUMBER() OVER (PARTITION BY vm.iAssetId ORDER BY vm.fSpeedKPH DESC) AS RN
from VehicleMonitoringLog vm inner join Geofences ge
on ge.iGeofenceId = vm.iGeofenceId
where vm.iGeofenceId != 1 AND vm.fSpeedKPH > 70
AND (vm.dtUTCDateTime > @dateMinusDay --<-- Instead of variable you can use GETDATE() - 1
AND vm.dtUTCDateTime < GETDATE())
)Q
WHERE RN = 1