如何将4个表数据合二为一

时间:2014-07-18 15:01:58

标签: sql tsql

我有4个表格,其中包含以下信息

Table 1 ------- date, route, qty1
table 2 ------- date, route, qty2
table 3 ------- date, route, qty3
table 4 ------- date, route, qty4

我需要加入这4个表来创建另一个具有以下结果的表

date, route, qty1, qty2, qty3, qty4 

所有表都没有必要相同的路由或日期,但如果他们这样做,我将需要查询匹配同一行下的信息。例如

Table 1 ------- date,    route,  qty1
                07/01/14   1      1
table 2 ------- date,    route, qty2
                07/01/14   1      2
table 3 ------- date,    route, qty3
                07/02/14   2      3
table 4 ------- date,    route, qty4
                07/03/14   1      4

结果应该是

date      route   qty1    qty2   qty3  qty4
07/01/14    1      1        2
07/02/14    2                      3
07/03/14    1                             4
有人可以帮帮我吗?

2 个答案:

答案 0 :(得分:3)

我会使用union all聚合:

select date, route, sum(qty1) as qty1, sum(qty2) as qty2,
       sum(qty3) as qty3, sum(qty4) as qty4
from ((select date, route, qty1 as qty1, NULL as qty2, NULL as qty3, NULL as qty4
       from table1
      ) union all
      (select date, route, NULL as qty1, qty2 as qty2, NULL as qty3, NULL as qty4
       from table2
      ) union all
      (select date, route, NULL as qty1, NULL as qty2, qty3 as qty3, NULL as qty4
       from table3
      ) union all
      (select date, route, NULL as qty1, NULL as qty2, NULL as qty3, qty4 as qty4
       from table4
      )
     ) t
group by date, route
order by date, route;

编辑:

如果您想要一个新表(而不仅仅是一个查询),请在into之后使用select子句。

答案 1 :(得分:0)

您可能希望将所有表外连接在一起。

http://technet.microsoft.com/en-us/library/ms187518(v=sql.105).aspx

示例:

DECLARE @tbl1 TABLE
(
    d DATE,
    r INT,
    q1 INT
)

DECLARE @tbl2 TABLE
(
    d DATE,
    r INT,
    q2 INT
)

DECLARE @tbl3 TABLE
(
    d DATE,
    r INT,
    q3 INT
)

DECLARE @tbl4 TABLE
(
    d DATE,
    r INT,
    q4 INT
)


INSERT INTO @tbl1 SELECT '2014-07-01', 1, 1
INSERT INTO @tbl2 SELECT '2014-07-01', 1, 2
INSERT INTO @tbl3 SELECT '2014-07-02', 2, 3
INSERT INTO @tbl4 SELECT '2014-07-03', 1, 4

SELECT d = COALESCE(t1.d, t2.d, t3.d, t4.d)
    , r = COALESCE(t1.r, t2.r, t3.r, t4.r)
    , t1.q1
    , t2.q2
    , t3.q3
    , t4.q4
FROM @tbl1 t1
FULL OUTER JOIN @tbl2 t2
    ON t1.d = t2.d
    AND t1.r = t2.r
FULL OUTER JOIN @tbl3 t3
    ON t1.d = t3.d
    AND t1.r = t3.r
FULL OUTER JOIN @tbl4 t4
    ON t1.d = t4.d
    AND t1.r = t4.r

结果:

d           r   q1      q2      q3      q4
2014-07-01  1   1       2       NULL    NULL
2014-07-02  2   NULL    NULL    3       NULL
2014-07-03  1   NULL    NULL    NULL    4