Reputation: 1376
I have a query like
SELECT 'Education' as Purpose,ate_sex, Age_range, COUNT(*) AS Total
FROM (
SELECT dbo.ClientMain.ate_sex, dbo.ClientMain.ate_Id,
CASE
WHEN ate_Age BETWEEN 15 AND 19 THEN '15-19'
WHEN ate_Age BETWEEN 20 AND 24 THEN '20-24'
WHEN ate_Age BETWEEN 25 AND 34 THEN '25-34'
WHEN ate_Age BETWEEN 35 AND 44 THEN '35-44'
WHEN ate_Age BETWEEN 45 AND 54 THEN '45-54'
WHEN ate_Age BETWEEN 55 AND 64 THEN '55-64'
ELSE '80+' END AS Age_range
FROM dbo.ClientMain
INNER JOIN dbo.ClientSub ON dbo.ClientMain.ate_Id = dbo.ClientSub.ate_Id
WHERE (dbo.ClientSub.chk_Name = N'Assistance')
) AS t group by ate_sex,Age_range
Which returns the data as:
But I want my result as when there is no record with he age range in 15-19, it have to return zero. As Education Male 15-19 0
These are my tables
Can anybody please modify my query to get zeros for no records.
Upvotes: 1
Views: 3551
Reputation: 17480
Use a LEFT JOIN
instead of INNER JOIN
Use ISNULL(COUNT(*), 0)
instead of COUNT(*)
. Alternatively, you can also use
Total = CASE WHEN COUNT(*) IS NULL THEN 0 ELSE COUNT(*) END
Upvotes: 3
Reputation: 1026
If you doesnt have data with male, 15-19 in any table, yet you still want it in result with count as "0". Try building a static table with possible rows and do a cross join with your resultset.
Upvotes: 0