我的数据如下:
Table
Group: "A" , Color: "Blue", Count: "400"
Group: "A" , Color: "Green", Count: "3"
Group: "A" , Color: "Yellow", Count: "6"
Group: "A" , Color: "Red", Count: "1"
Group: "B" , Color: "Purple", Count: "243"
Group: "B" , Color: "Green", Count: "2"
Group: "B" , Color: "Yellow", Count: "7"
如何查询此数据以获得最受欢迎(按计数)颜色的每个组。所以结果看起来像这样:
Result
Group: "A", Color: "Blue"
Group: "B", Color: "Purple"
答案 0 :(得分:6)
SELECT Group, Color
FROM MyTable t
INNER JOIN (SELECT Group, Max(CAST(Count as int)) as Ct
FROM MyTable
GROUP BY Group) Sub
ON sub.group = t.group
AND sub.ct = t.count
另外,请勿指定字段GROUP
或COUNT
。它们是关键词,会导致头痛和心碎。
答案 1 :(得分:0)
这也应该有效:
SELECT t.Group,
t.Color,
t.Count
FROM (SELECT Group,
Color,
Count,
ROW_NUMBER() OVER(PARTITION BY Group ORDER BY CAST(Count AS INT) DESC) AS num
FROM Table) AS t
WHERE t.num = 1