如何从3个表(SUM)创建正确的选择查询?

时间:2017-10-04 20:19:39

标签: sql sql-server

我有3张桌子:

+-----+---------+
|cl_id|  name   |
+-----+---------+
|   1 |   adaf  |
|   2 |   rich  | - clients
|   3 |   call  |
|   4 |   alen  |
|   5 | courney |
|   6 |  warren |
+-----+---------+

+-----+---------+
|cl_id|  data   |
+-----+---------+
|   1 |      13 |
|   2 |    1000 | - table1
|   5 |      0  |
|   6 |      0  |
+-----+---------+

+-----+---------+
|cl_id|  data   |
+-----+---------+
|   2 |    -355 | - table2
|   3 |  35     | 
|   3 |  10     | 
|   5 |     46  |
|   5 |     50  |
|   5 |     10  |
+-----+---------+

我必须将这三个表组合在一起,所以结果应该是:

+-----+---------+--------+---------+
|cl_id| name    |data_tb1|data_tb2 |
+-----+---------+--------+---------+
|   1 |   adaf  |    13  |      0  |
|   2 |   rich  |   1000 |    -355 |
|   3 |   call  |     0  |      45 |
|   4 |   alen  |     0  |      0  |
|   5 |  courney|     0  |     106 |
|   6 |  warren |     0  |      0  |
+-----+---------+--------+---------+

它应该从table1和table2输出所有客户端及其SUM(data)。客户一对一。

提前致谢

2 个答案:

答案 0 :(得分:4)

只需使用LEFT JOINGROUP BY

即可
SELECT c.cl_id,
       c.name,
       COALESCE(SUM(t1.data), 0) AS data_tb1,
       COALESCE(SUM(t2.data), 0) AS data_tb2
FROM clients c
     LEFT JOIN table1 t1 ON c.cl_id = t1.cl_id
     LEFT JOIN table2 t2 ON c.cl_id = t2.cl_id
GROUP BY c.cl_id,
         c.name
ORDER BY c.cl_id;

答案 1 :(得分:0)

如果您使用的是SQL Server,请按以下方式使用Left Join

SELECT C.cl_id,
       C.name,
       SUM(ISNULL(T.data, 0)) data_tb1,
       SUM(ISNULL(T1.data, 0)) data_tb2
FROM
(
    SELECT *
    FROM clients
) C
LEFT JOIN table1 T ON T.cl_id = C.cl_id
LEFT JOIN table2 T1 ON T1.cl_id = C.cl_id
GROUP BY C.cl_id,
         C.name
ORDER BY C.cl_id;

期望输出:

+-----+---------+--------+---------+
|cl_id| name    |data_tb1|data_tb2 |
+-----+---------+--------+---------+
|   1 |   adaf  |    13  |      0  |
|   2 |   rich  |   1000 |    -355 |
|   3 |   call  |     0  |      45 |
|   4 |   alen  |     0  |      0  |
|   5 |  courney|     0  |     106 |
|   6 |  warren |     0  |      0  |
+-----+---------+--------+---------+