I have 3 tables: Vehicle, type and color
Vehicle
id brand type_id color_id
1 Toyota 1 2
2 Toyota 2 3
3 GMC 2 1
4 BMW 2 1
Type
id name
1 Truck
2 Car
Color
id name
1 White
2 Red
3 Black
I want to get the count of each combination of type and color including 0 values, like this:
type.name color.name count
Truck White 0
Truck Red 1
Truck Black 0
Car White 2
Car Red 0
Car Black 1
I tried this query below
SELECT type.name, color.name, count(vehicle.id) count
FROM vehicle
RIGHT JOIN type on vehicle.type_id = type.id
RIGHT JOIN color on color.id = vehicle.color_id
GROUP BY type.name, color.name
but it doesn't produce zero values:
type.name color.name count
Truck Red 1
Car White 2
Car Black 1
Is there a neat query to achieve the first results?
2条答案
按热度按时间2skhul331#
As mention @jarlh in comments, this can be done using
CROSS JOIN
:Or simply :
Results :
Demo here
2g32fytz2#
Here's another way of doing it.
with record_count as (
select
b.id [typeid],
b.name [typename],
c.id [colorid],
c.name,
[colorname],
count(*) record_count
from vehicle a
left join type b on a.type_id = b.id
left join color c on a.color_id = c.id
group by b.id, b.name, c.id, c.name
)
select a.typename, a.colorname, isnull(b.record_count,0) count
from (
select distinct type.id [typeid], type.name [typename], color.id
[colorid], color.name [colorname]
from vehicle , type, color
) as a
left join record_count b on a.typeid = b.typeid
and a.colorid = b.colorid