我有一张桌子,上面放着汽车和车库。每辆车仅在一个车库中列出,但是一个车库中可以有很多车。我想知道车库中每种汽车有多少种。每辆车在数据库中都有自己的行。
这张桌子看起来像这样。
+-------+--------+-----+
|carType| garage |id |
+-------+--------+-----+
| 1 | 1 | 1 |
+-------+--------+-----+
| 1 | 1 | 2 |
+-------+--------+-----+
| 1 | 2 | 3 |
+-------+--------+-----+
| 2 | 2 | 4 |
+-------+--------+-----+
这就是我想要的。
+-------+------------+--------+
|carType| carCount | garage |
+-------+------------+--------+
| 1 | 2 | 1 |
+-------+------------+--------+
| 1 | 1 | 2 |
+-------+------------+--------+
| 2 | 1 | 2 |
+-------+------------+--------+
问题是我不知道查询的外观。
答案 0 :(得分:0)
您只需要GROUP BY
carType
和 garage
:
SELECT carType, COUNT(*) AS carCount, garage
FROM cars
GROUP BY carType, garage
输出:
carType garage carCount
1 1 2
1 2 1
2 2 1
答案 1 :(得分:0)
我第一次尝试回答这里的问题,希望它能解决问题! 就像戈登所说的“提示分组依据”一样,如果在下面不正确,请大声疾呼戈登。
with t
as
(select * from(values(1,1,1),(1,1,2),(1,2,3),(2,2,4)) as t (carType,garage,id))
select carType, count(id) as carCount, garage
from t
group by carType, garage