简体   繁体   中英

get all rows from one table, sum on column from a second table using a where clause

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!

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM