MySQL-比较两个表并将它们相加

时间:2019-03-13 16:14:02

标签: mysql join select sum

我正在努力比较()两个表与彼此之间的比较。

例如,我有以下2个表:

表1

tablename: master
col1: code
col2: categories

数据

 categories     code
 GP              a01
 GP              a02
 GP              a03
 DENTAL          d01
 DENTAL          d02
 DENTAL          d02
 DENTAL          d03
 DENTAL          d04
 OPTOM           o01

表2

tablename: submissions
col1: code

数据

  code
  a01
  a02
  a03
  d04
  d01
  o01
  a03

我需要通过代码链接两个表,以查看谁在提交表中提交了哪些人,然后又没有人计算出总百分比:

我的理想结果:

categories   codes_total    received    outstanding   percentage received
category 1       200           40            160             20%
category 2       100           10            90              10%

除此以外,我不知道该从哪里真正开始??:

 SELECT categories, sum(total1), sum(total2), sum(total3) FROM (

  (SELECT categories, count(*) t1
  FROM master) as total1,

  (SELECT categories, count(*) t2
  FROM master
  LEFT JOIN submissions ON submissions.code=master.code) 
  )as total2,

  (SELECT categories, count(*) t3
  FROM master
  LEFT JOIN submissions ON submissions.code=master.code
  WHERE submissions.code IS NULL) 
  )as total3

) FOO
  GROUP BY categories

我朝着正确的方向前进?

1 个答案:

答案 0 :(得分:1)

select master.categories, count(*) codes_total,
        (select count(*)
                    FROM master master2
                            inner join submissions on master2.code = submissions.code
                    where master2.categories = master.categories) received,
        count(*) - (select count(*)
                    FROM master master2
                            inner join submissions on master2.code = submissions.code
                    where master2.categories = master.categories) `outstanding`,

        (select count(*)
                    FROM master master2
                            inner join submissions on master2.code = submissions.code
                    where master2.categories = master.categories) / count(*) * 100 as `percentage received`

from master

group by master.categories
order by master.categories;