尽管存在错误,但下面的查询似乎仍然有效。
Color
列不属于聚合函数,但我不想按Color
分组。我想返回颜色的最低优先级分组的车辆。
我希望下面的内容已经足够了--我希望能得到一个快速的答案,但如果有必要的话,我会更详细地讨论。
SELECT alert.VehicleID,
min(hotcol.[Priority]) as [Priority]
min(hotcol.Color) as Color,
FROM [ALERTS] alert
INNER JOIN [HOTLISTS] hotlist ON alert.[HotlistID] = hotlist.[HotlistID]
INNER JOIN [HOTLIST_COLORS] hotcol ON hotlist.ColorID = hotcol.ColorID
WHERE VehicleID = 17513851
GROUP BY alert.VehicleID
发布于 2014-11-10 11:50:24
您可以使用排名函数ROW_NUMBER
来完成此操作。就像这样:
WITH CTE
AS
(
SELECT
alert.VehicleID,
hotcol.Color,
hotcol.[Priority],
ROW_NUMBER() OVER(PARTITION BY alert.VehicleID
ORDER BY hotcol.[Priority]) AS RN
FROM [ALERTS] alert
INNER JOIN [HOTLISTS] hotlist ON alert.[HotlistID] = hotlist.[HotlistID]
INNER JOIN [HOTLIST_COLORS] hotcol ON hotlist.ColorID = hotcol.ColorID
WHERE VehicleID = 17513851
)
SELECT
VehicleID,
Color,
[Priority]
FROM CTE
WHERE rn = 1;
ROW_NUMBER
函数将为每个alert.VehicleID
提供一个排序编号,每个组将由priority
排序。然后,WHERE rn = 1
将过滤除最小行外的所有行,其中包含rn = 1
。
https://stackoverflow.com/questions/26843130
复制相似问题