查询两个表和总和

时间:2016-12-19 18:10:37

标签: mysql

如何查询两个表并对结果求和。我的意思是我有桌子

Job
-----
job_id
job_cost

第二张表

worker
------
worker_id
worker_name

这是数据透视表

finished_work
--------
job_id
worker_id
hours

因此,我希望将finished_work的所有小时数加起来并基于job_cost来显示所有已完成作品的总数。实施例

work_1 - 40 hours * 5(job_cost) = 200
work_2 -3 hours * 15 = 45

total = 245

感谢任何帮助

1 个答案:

答案 0 :(得分:0)

执行此操作的最佳方法可能是使用proc sql。这是一个示例,我使用两个pro sql语句打印出您可能想要的中间文件。如果没有,你可以运行第二个SQL查询。

首先我们创建您的数据集:

data job;
job_id = 1;
job_cost = 5;
output;
job_id = 2;
job_cost = 10;
output;
run;

data worker;
worker_id = 1;
worker_name = 'Jon';
output;
worker_id = 2;
worker_name = 'Peter';
output;
run;

data finished;
job_id = 1;
worker_id = 1;
hours = 3;
output;
job_id = 2;
worker_id = 2;
hours = 5;
output;
run;

这里是中间的sql文件:

proc sql noprint;
create table projects as
       select a.worker_name,b.hours,c.job_cost,b.hours*c.job_cost as total
             from worker as a
       left join finished as b
           on a.worker_id = b.worker_id
       left join job as c
           on b.job_id = c.job_id;quit;

这是一步到位的最终答案:

proc sql noprint;
     create table project as
           select sum(total) as Grand_Total
                  from(select a.worker_name,b.hours,c.job_cost,b.hours*c.job_cost as total
                              from worker as a
                       left join finished as b
                            on a.worker_id = b.worker_id
                       left join job as c
                            on b.job_id = c.job_id);quit;

对SAS感到抱歉 - 认为这是来自SAS问题。 sql语句对mysql有效,只需删除proc sql noprint行

即可