我有看起来像这样的数据:
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"
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。它们是关键字,将导致头痛和令人伤心。
GROUP
COUNT