如何连接空白表

时间:2015-06-12 13:39:39

标签: mysql sql-server sql-server-2008

表1

url('../img/*.jpg')

表2

Names   assigned
Xyz.        123
Wxy.        456

表3

Names. Unassigned
Xyz.        789
Tty.        123

表4

Names.    Closed
Wxy.        456
Twr.        123

此表格不包含任何值

我想输出

Names.  Open

如何加入他们?

1 个答案:

答案 0 :(得分:0)

SELECT
    n.NAMES,
    ISNULL(t1.Assigned, 0) Assigned,
    ISNULL(t1.Unassigned, 0) Unassigned,
    ISNULL(t1.Closed, 0) Closed,
    ISNULL(t1.Open, 0) Open
FROM
    (           SELECT NAMES FROM Table1
        UNION   SELECT NAMES FROM Table2
        UNION   SELECT NAMES FROM Table3
        UNION   SELECT NAMES FROM Table4
    ) AS n
    LEFT JOIN (SELECT NAMES, SUM(Assigned) FROM Table1 GROUP BY NAMES) t1 ON n.NAMES = t1.NAMES
    LEFT JOIN (SELECT NAMES, SUM(Unassigned) FROM Table2 GROUP BY NAMES) t2 ON n.NAMES = t2.NAMES
    LEFT JOIN (SELECT NAMES, SUM(Closed) FROM Table3 GROUP BY NAMES) t3 ON n.NAMES = t3.NAMES
    LEFT JOIN (SELECT NAMES, SUM(Open) FROM Table4 GROUP BY NAMES) t4 ON n.NAMES = t4.NAMES