Skip to content
Advertisement

counting totals after left join and requiring 0 for a NULL variable – SQL Server

I am using SQL Server Management Studio 2012 and I am running the following query:

SELECT T1.ID, COUNT(DISTINCT T2.APPOINTMENT_DATE) AS [TOTAL_APPOINTMENTS]
FROM T1
LEFT JOIN T2
ON T1.ID = T2.ID
WHERE T2.APPOINTMENT_DATE > '2019-01-01' AND T2.APPOINTMENT_DATE < '2020-01-01'
AND (T1.ID = 1 OR T1.ID = 2 OR T1.ID = 3)

I would like the total number of appointments for these 3 individuals for now. Then, I will include everyone in Table 1. Table 1 gives me the ID (one row per individual), Table 2 gives me all appointments across different days per individual.

The results I get are:

ID  TOTAL_APPOINTMENTS
1         12
2         3

But I would like:

ID  TOTAL_APPOINTMENTS
1         12
2         3
3         0

Can you please advise?

Advertisement

Answer

Move the WHERE conditions on the second table to the ON clause:

SELECT T1.ID, COUNT(DISTINCT T2.APPOINTMENT_DATE) AS [TOTAL_APPOINTMENTS]
FROM T1 LEFT JOIN
     T2
     ON T1.ID = T2.ID AND
        T2.APPOINTMENT_DATE > '2019-01-01' AND
        T2.APPOINTMENT_DATE < '2020-01-01'
WHERE T1.ID IN (1, 2, 3);

Note that the conditions on the first table remain in the WHERE clause. Also, IN is simpler than a bunch of OR conditions.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement