Reputation: 55
I want to get all rows from table1 and I want to get a total of a column in table3 for each person in table1. I am able to do this if I don't use a where clause anywhere in my query (in the sub select, inner join or regular where clause). If I use a where clause like below, only the people in table1 that have records in table2 between a supplied date and have been verified.
What I want is all rows from table1 but sum only the records in table2 that are between the supplied date and have been verified.
Is there any way to do this in a single query?
SELECT table1.ID
, table1.LName
, table1.FName
, (Select SUM(table3.DollarValue) Where table2.Verified = 1) AS total
FROM table3
INNER JOIN table2 ON table3.IncentiveID = table2.IncentiveID
RIGHT OUTER JOIN table1 ON table2.ID = table1.ID
Where table2.date >= '1/1/2012'
AND table2.date <= '12/31/2012'
AND table2.Verified = 1
Group By table1.ID, table1.LName, table1.FName, table2.Verified
Order By table1.LName, table1.FName
Thank you in advance for any help!
Upvotes: 1
Views: 4914
Reputation: 247690
Based on your description, it sounds like you want something like the following. Which places your table2
and table3
join and sum()
in a subquery with the WHERE
filtering and then joins that result to table1
:
SELECT t1.ID,
t1.LName,
t1.FName,
IsNull(t.total, 0) as Total
FROM table1 t1
LEFT JOIN
(
SELECT t2.id, SUM(t3.DollarValue) as total
FROM table2 t2
INNER JOIN table3 t2
on t2.IncentiveID = t3.IncentiveID
WHERE t2.date >= '2012-01-01'
AND t2.date <= '2012-12-31'
AND t2.Verified = 1
GROUP BY t2.id
) t
on t1.ID = t.ID
Order By t1.LName, t1.FName;
Upvotes: 3