SQL组合表

时间:2013-11-15 19:06:46

标签: sql sql-server

我有两张表如下:

表1:

f1      f2
1        2
3        4
5        6
7        8

表2:

f1      f3    f4
 1       R    20
 1       m    10
 1       m    30
 3       m    5
 5       R    20

所以现在我需要一个像这样的表:

f1      f2      SUM(f4 where f3=m)
1       2           40
3       4           5
5       6           null
7       8           null

换句话说,如果f1存在于table2中并且f3 ='m',那么得到它的总和,否则只需从table1中选择所有数据。

我尝试了以下代码:

SELECT T1.* , T2.SUM(f4)
FROM Table1 AS T1
LEFT OUTER JOIN Table2 AS T2 ON T1.f1 = T2.f1
WHERE T2.f3='m'

这只显示Table2中存在的一个,如果我这样做:

SELECT T1.* , T2.SUM(f4)
FROM Table1 AS T1
LEFT OUTER JOIN Table2 AS T2 ON T1.f1 = T2.f1 AND T2.f3='m'

为f3显示20,为1显示5和60。

3 个答案:

答案 0 :(得分:0)

您需要GROUP BY

SELECT  T1.f1 ,
        T1.f2 ,
        T2.SUM(f4)
FROM    Table1 AS T1
        LEFT OUTER JOIN Table2 AS T2 
        ON T1.f1 = T2.f1
        AND T2.f3 = 'm'
GROUP BY T1.f1 ,
         T1.f2

答案 1 :(得分:0)

select T1.F1, T1.F2, sum(T2.f4)
from Table1 T1
left outer join  Table2 as T2
on (T1.F1 = T2.F1 and T2.F3 = 'm')
group by T1.F1 , T1.F2

答案 2 :(得分:0)

SELECT     dbo.tab1.f1, dbo.tab1.f2, CASE WHEN f3 = 'm' THEN SUM(f4) ELSE NULL END AS    Expr1
FROM       dbo.tab1 LEFT OUTER JOIN        
           dbo.tab2 ON dbo.tab1.f1 = dbo.tab2.f1 AND dbo.tab2.f3 = 'm'
GROUP BY   dbo.tab1.f1, dbo.tab1.f2, dbo.tab2.f3