尽管错误,但下面的查询似乎有效。
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
答案 0 :(得分:1)
您可以使用排名功能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
之外的最小行以外的所有行。