9

我有两张表,分别命名为 Table-A 和 Table-B。请参考给定的表格。我想在两个表中汇总“值”列后加入这些。例如;

表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

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

4

3 回答 3

9

试试这个——

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
于 2013-06-10T05:48:39.793 回答
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
于 2013-06-10T05:53:02.410 回答
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
于 2013-06-10T05:57:10.383 回答