使用Aggregate值连接表

时间:2013-06-10 05:46:24

标签: sql-server join

我有两个表,名为Table-A和Table-B。请参考给定的表格。我想在两个表中获取“Value”列的聚合后加入这些。例如;

表格-A

     Name    Value1
      ABC     10
      ABC     18
      ABC     12
      DEF     5
      XYZ     15
      XYZ     16

表格-B

     Name    Value2
      ABC     15
      ABC     5
      XYZ     9

我的预期结果是,

结果

     Name    Value1   Value2
      ABC      40       20
      DEF      5        0
      XYZ      31       9

希望你理解我的问题。任何帮助将不胜感激。

3 个答案:

答案 0 :(得分:7)

试试这个 -

SELECT 
      a.Name
    , Value1 = ISNULL(Value1, 0)
    , Value2 = ISNULL(Value2, 0)
FROM (
    SELECT 
          Name
        , Value1 = SUM(Value1)
    FROM dbo.[TABLE-A]
    GROUP BY Name
) a
LEFT JOIN (
    SELECT 
          Name
        , Value2 = SUM(Value2)
    FROM dbo.[TABLE-B]
    GROUP BY Name
) b ON a.Name = b.Name

答案 1 :(得分:1)

SELECT [TAB-A].NAME, VALUE1, VALUE2 FROM
(SELECT NAME, SUM(VALUE1) VALUE1 FROM [TABLE-A] GROUP BY NAME) [TAB-A] LEFT JOIN
(SELECT NAME, SUM(VALUE2) VALUE2 FROM [TABLE-B] GROUP BY NAME) [TAB-B]
ON [TAB-A].NAME = [TAB-B].NAME

答案 2 :(得分:1)

SELECT  
      COALESCE(A.Name, B.Name)
    , (CASE WHEN A.value IS NULL THEN 0 ELSE A.value END) AS Value1
    , (CASE WHEN B.value IS NULL THEN 0 ELSE B.value END) AS Value2 
FROM (
    SELECT Name, SUM(Value) AS Value 
    FROM #A GROUP BY Name
) AS A 
FULL JOIN (
    SELECT Name, SUM(Value) AS Value 
    FROM #B GROUP BY Name
) AS B ON A.Name = B.Name

DROP TABLE #A
DROP TABLE #B