gpt4 book ai didi

MySQL - 比较两个表并对它们求和

转载 作者:行者123 更新时间:2023-11-29 09:49:09 25 4
gpt4 key购买 nike

我正在努力研究如何将两个表相互比较,同时对它们进行总计(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

我正朝着正确的方向前进???

最佳答案

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;

关于MySQL - 比较两个表并对它们求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55146516/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com