The following code takes a table containing vehicle names, and a table containing region names and combines them into a results table.
I then perform a COUNT on the results table to show how many vehicles there are per region.
I need to amend the code to force ALL regions and ALL vehicles to be counted up. Currently the COUNT statement does not show any regions that contain no vehicles (I have manually deleted some entries from the results to show this). Can anyone illustrate a quick way to do this? I am using SQL 2012 and hoped there would be an easy solution…

For the purposes of answering the question please assume that the two original tables are no longer accessible, and we are now only working with @tbl_results. Thank you.
Note: I know I can do this directly from the vehicle and region tables but I need to use a table variable of results for other processes in my real work.
DECLARE @tbl_vehicles TABLE (vehicleID int, vehicleName nvarchar(100))
DECLARE @tbl_regions TABLE (regionID int, regionName nvarchar(100))
DECLARE @tbl_results TABLE (regionID int, regionName nvarchar(100), vehicleID int, vehicleName nvarchar(100))
INSERT INTO @tbl_regions (regionID, regionName) VALUES (1, 'England')
INSERT INTO @tbl_regions (regionID, regionName) VALUES (2, 'United States')
INSERT INTO @tbl_regions (regionID, regionName) VALUES (3, 'Arctic')
INSERT INTO @tbl_vehicles (vehicleID, vehicleName) VALUES (1, 'Planes')
INSERT INTO @tbl_vehicles (vehicleID, vehicleName) VALUES (2, 'Trains')
INSERT INTO @tbl_vehicles (vehicleID, vehicleName) VALUES (3, 'Automobiles')
DECLARE @i INT
SET @i = 0
WHILE @i < 100
BEGIN
INSERT INTO @tbl_results
(regionID, regionName, vehicleID, vehicleName)
SELECT
r.regionID, r.regionName, v.vehicleID, v.vehicleName
FROM
@tbl_regions r CROSS JOIN
@tbl_vehicles v
WHERE
(r.regionID = CAST(RAND() * 4 AS INT)) AND
(v.vehicleID = CAST(RAND() * 4 AS INT))
SET @i = @i + 1
END
-- remove trains in the arctic for count example
DELETE FROM @tbl_results WHERE (regionID=3) AND (vehicleID=2)
-- this statement needs to include ALL vehicles and ALL regions (even if no vehicles are found at a region)
SELECT
regionName,
vehicleName,
COUNT(*) as VehicleCount
FROM
@tbl_results
GROUP BY
regionID,
regionName,
vehicleID,
vehicleName
ORDER BY regionName, vehicleName
1 Answer