在公共列上加入2个SELECT语句

时间:2014-02-10 08:26:14

标签: sql oracle

我有两个选择语句,例如bellow:

SELECT t.name, SUM(t.number) 
FROM table1 t 
WHERE t.something = '1' 
GROUP BY t.name

SELECT v.name, SUM(v.number2) 
FROM table2 v 
WHERE v.somethingElse = '2' 
GROUP BY v.name

这两个表格的结果都有一个共同的列名称'我想组合两个SELECT语句,所以我有一个名称列,两个总和显示在他们的共同点名称旁边。

我已经尝试了一个完整的外部加入,但我似乎无法让它工作。

SELECT t.name, SUM(t.number) 
FROM table1 t 
FULL OUTER JOIN (SELECT v.name, SUM(v.number2) FROM table2 v 
WHERE v.somethingElse = '2' GROUP BY v.name) 
ON t.name = v.name 
WHERE t.something = '1' 
GROUP BY t.name

希望有人可以指出我的愚蠢错误,或者我应该如何做到这一点。

谢谢。

更新:不断收到错误'错过右括号'。看看sqlfiddle http://sqlfiddle.com/#!4/b04c4/4

3 个答案:

答案 0 :(得分:2)

在子查询上创建值为0的虚拟列,并使用union all按名称对它们求和。像这样的东西

select name, sum(number1),sum(number2) from ( 
    SELECT t.name, SUM(t.value) as number1 , 0 as number2
        FROM table1 t 
        WHERE t.value = '1' 
        GROUP BY t.name
    UNION
    SELECT v.name, 0 as number1 ,SUM(v.value) as number2
        FROM table2 v 
        WHERE v.value = '2' 
        GROUP BY v.name
) group by name;

这里是sql fiddle

答案 1 :(得分:2)

尝试这种方式:

select A.Name, A.cnt1, B.cnt2 
from(
      SELECT t.name, SUM(t.number) cnt1  
      FROM table1 t 
      WHERE t.something = '1' 
      GROUP BY t.name
   ) A
left join ( 
            SELECT v.name, SUM(v.number2)  cnt2
            FROM table2 v 
            WHERE v.somethingElse = '2' 
            GROUP BY v.name
           ) B on B.name= A.name

答案 2 :(得分:1)

我不知道为什么FULL OUTER JOIN不适合你,但是以下JOIN有效并且给出了你期望的结果:

DECLARE @table1 TABLE
(
  name nvarchar(50), 
  number int
)

DECLARE @table2 TABLE
(
  name nvarchar(50), 
  number int
)

INSERT INTO @table1 VALUES ('name1', 1)
INSERT INTO @table1 VALUES ('name2', 2)
INSERT INTO @table1 VALUES ('name3', 5)
INSERT INTO @table2 VALUES ('name1', 3)
INSERT INTO @table2 VALUES ('name2', 4)
INSERT INTO @table2 VALUES ('name4', 6)

SELECT 
    (CASE WHEN t1Result.name IS NOT NULL THEN t1Result.name
        ELSE t2Result.name
    END) As 'name'
    , t1Result.Sum As 'Sum of table1', t2Result.Sum As 'Sum of table2'
FROM
(
    (
        SELECT name, SUM(number) As 'Sum'
        FROM @table1
        GROUP BY name
    ) As t1Result       
    FULL OUTER JOIN 
    (
        SELECT name, SUM(number) As 'Sum'
        FROM @table2
        GROUP BY name
    ) As t2Result
    ON t1Result.name = t2Result.name
)   

结果是:

name    Sum of table1   Sum of table2
name1       1               3
name2       2               4
name3       5               NULL
name4       NULL            6

未包含WHERE列的somethingElse过滤器,可以添加到内部查询 t1Resultt2Result

编辑:Oracle查询SqlFiddle

上的结果