SQL Distinct基于两列Order By计数

时间:2014-09-20 12:07:25

标签: sql tsql

-------------------------
|  ID | Make  | Model   |
|   1 | Ford  | Cortina |
|   2 | Ford  | Escort  |
|   3 | Ford  | Cortina |
|   4 | VW    | Golf    |
|   5 | Audi  | Quattro |
|   6 | Ford  | Cortina |
|   7 | VW    | Golf    |
|   8 | Ford  | Escort  |
|   9 | Fiat  | Uno     |
|  10 | Honda | Civic   |
-------------------------

我希望能够根据DISTINCT Make& amp选择前5行。带有计数的模型,结果如下: -

----------------------------
|  Count | Make  | Model   |
|      3 | Ford  | Cortina |
|      2 | Ford  | Escort  |
|      1 | Ford  | Cortina |
|      1 | VW    | Golf    |
|      1 | Audi  | Quattro |
----------------------------

1 个答案:

答案 0 :(得分:2)

尝试使用此查询:

SELECT TOP 5 COUNT(ID) as COUNT, MAKE, MODEL
FROM yourtable
GROUP BY MAKE, MODEL
ORDER BY COUNT(ID) DESC, MAKE

Demo here