1

我有两个表如下: -

           Table 1                      Table 2 
         date     value             date     value 
         1120101   v11              1120102   v21
         1120202   v12              1120303   v22  
         1120203   v13              1120104   v23  

获取以下输出的 sql 查询是什么

        date         value 
       1120101       (v11)
       1120102       (v12+v21)
       1120103       (v13+v22)
       1120104       ( v23)  

我厌倦了以下查询,但未能获得所需的输出

select table1.date,
       table2.date,
       table1.delta+table2.delta as delta 
from table1,
     table2   
where table1.date=table2.date;

提前致谢 。

4

2 回答 2

6
SELECT date, SUM(value)
FROM
(
    SELECT date, value FROM table1
    UNION ALL
    SELECT date, value FROM table2
) a
GROUP BY date
于 2012-11-27T05:48:37.613 回答
2

玩子查询和联合:

SELECT
    c.date,
    COALESCE(a.value, 0) + COALESCE(z.value,0)
FROM (
    SELECT
        date
    FROM table1
    UNION
        SELECT date
    FROM table2
) AS c
LEFT OUTER JOIN table1 a
    ON a.date = c.date
LEFT OUTER JOIN table2 z
    ON z.date = c.date
于 2012-11-27T05:52:37.137 回答