聚合查询分组

时间:2014-11-10 11:46:23

标签: sql-server

尽管错误,但下面的查询似乎有效。

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

1 个答案:

答案 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之外的最小行以外的所有行。