获取一个表中的所有行,使用where子句对第二个表中的列求和

时间:2013-01-10 17:02:37

标签: sql sql-server sum aggregate-functions

我想获取table1中的所有行,并且我想在table3中为table1中的每个人获取总共一列。如果我不在查询中的任何地方使用where子句(在sub select,inner join或regular where子句中),我可以这样做。如果我使用如下的where子句,则只有table1中在提供的日期之间有table2记录并且已经过验证的人员。

我想要的是来自table1的所有行,但只汇总table2中提供的日期和已经过验证的记录。

有没有办法在单个查询中执行此操作?

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

提前感谢您的帮助!

1 个答案:

答案 0 :(得分:3)

根据您的描述,听起来您需要以下内容。将table2table3加入以及sum()放入带有WHERE过滤的子查询中,然后将该结果加入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;