简体   繁体   English

如何联接两个表并基于不同的列在Mysql中汇总它们的列

[英]How to Join two tables and sum their columns across in Mysql based on distinct column

I am joining two tables by the regNo column. 我通过regNo列连接两个表。 I want to add the points of Table1.points and Table2.points where the regNo matches and just incase it doesn't match I also want it be included with its points in the list as shown in the image bellow 我想在RegNo匹配的地方添加Table1.points和Table2.points的点,以防万一它不匹配,我也希望将它的点包括在列表中,如下图所示 来自两个表1和表2的预期结果

I have read through the existing problems but not finding the solution to this eg How can I sum columns across multiple tables in MySQL? 我已经阅读了现有问题,但没有找到解决方案,例如, 如何在MySQL的多个表中汇总列?

(
    SELECT `Ex`.regNo,(`In`.`points`+`Ex`.`points`) AS 'Points' 
    FROM Table1`In` 
    LEFT JOIN Table2`Ex` ON `In`.`regNo` = `In`.`regNo`
)
UNION
(
    SELECT`Ex`.regNo,(`In`.`points`+`Ex`.`points`) AS 'Points' 
    FROM Table1`In` 
    RIGHT JOIN Table2`Ex` ON `In`.`regNo` = `In`.`regNo`
);

I want it to give the list arranged as per unique (DISTINCT) regNo 我希望它提供按照唯一(DISTINCT)reg排列的列表

You need UNION followed by GRoUP BY : 您需要UNION后跟GRoUP BY

SELECT regNo, SUM(points) AS total
FROM (
    SELECT regNo, points
    FROM Table1

    UNION ALL

    SELECT regNo, points
    FROM Table2
) AS u
GROUP BY regNo

You are looking for a FULL JOIN between both tables. 您正在寻找两个表之间的FULL JOIN

SELECT 
    COALESCE(t1.id, t2.id) id
    COALESCE(t1.regNo, t2.regNo) regNo
    COALESCE(t1.points, 0) +  COALESCE(t2.points 0) points
FROM
    table1 t1
    FULL JOIN table2 t2 on t1.regNo = t2.regNo

NB : you did not specify what you expect to be done to generate the new id so by default the above query will display the table1.id if available, else table2.id . 注意:您未指定生成新id预期操作,因此默认情况下,以上查询将显示table1.id如果可用),否则显示table2.id

If you would better generate a new, auto-incremented field, then : 如果最好生成一个新的,自动递增的字段,则:

SET @i=0;
SELECT 
    @i:=@i+1 id
    COALESCE(t1.regNo, t2.regNo) regNo
    COALESCE(t1.points, 0) +  COALESCE(t2.points 0) points
FROM
    table1 t1
    FULL JOIN table2 t2 on t1.regNo = t2.regNo

Please check this. 请检查一下。 You need to use full outer join and null replacement before aggregation 您需要在聚合之前使用full outer join和空替换

select 
   COALESCE(table1.regno, table2.regno) regno,
   sum(COALESCE(table1.points,0)) + sum(COALESCE(table2.points,0)) points
from Table1 
full outer join Table2 
  on table1.regno = table2.regno
group by 
  COALESCE(table1.regno, table2.regno)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM