3个表中的和值

时间:2014-03-12 14:43:36

标签: sql

表1

JH。 “作业HDR”

job-date     job-disp  job-dept  job-route  job-id  job-no
01/04/2013     6467       abc       123        22    81088
01/04/2013     6468       abc       987        36    82568

表2

RH。 “REC-充电”

charge-type    rec-id  base-sales-value
XYZ             22          700

表3

RC。 “REC-成本”

charge-type    rec-id  base-cost-value
XYZ             22          300

我需要能够从这个

的工作中获利
700 - 300 = 400

这是我已经到达的地方

SELECT jh."job-date", jh."job-disp", jh."job-dept", jh."job-route", rc."charge-type",rh."charge-type",
SUM(rc."base-cost-value") as COSTS, 
SUM(rh."base-sales-value") as SALES,
SUM(rh."base-sales-value") - SUM(rc."base-cost-value") as PROFIT
FROM MSN.PUB."rec-chg" rh, PUB."job-hdr" jh, pub."rec-cost" rc
WHERE jh."job-date" between '2013-04-01' and '2013-04-30'
and jh."job-id" = rc."rec-id"
and rc."rec-id" = rh."rec-id"
and jh."grp-id" = '0'
and jh."job-status"<>'D'
and jh."job-no" = '81088'
and rc."charge-type" = rh."charge-type"
Group by jh."job-date", jh."job-disp", jh."job-dept", jh."job-route",rc."charge- type",rh."charge-type"

这根本没有给我很好的结果,我知道我离开了。我只需要朝着正确的方向前进。

2 个答案:

答案 0 :(得分:0)

将利润更新为:

SUM(rh."base-sales-value" - rc."base-cost-value") as PROFIT

将您的论坛更新为:

group by jh."job-id", rc."rec-id", rh."rec-id"

这应该会给你想要的结果(希望如此)。抱歉没有时间自己测试一下。主要关注的是group by,它应该应用于一个字段,该字段将为您想要运行总和的其他字段返回多个结果。

答案 1 :(得分:0)

您的问题似乎有点含糊不清,无论您是想按作业还是按收费类型获得结果。在任何一种情况下,您都需要在执行join之前聚合结果。以下查询在作业级别执行此操作:

SELECT jh."job-date", jh."job-disp", jh."job-dept", jh."job-route", 
       COSTS, SALES, SALES - COSTS as PROFIT
FROM PUB."job-hdr" jh left outer join
     (select rh."rec-id", SUM(rh."base-sales-value") as SALES
      from MSN.PUB."rec-chg" rh
      group by rh."rec-id"
     ) rh
     on jh."job-id" = rh."rec-id" left outer join
     (select rc."rec-id", SUM(rc."base-cost-value") as COSTS
      from pub."rec-cost" rc
      group by rc."rec-id"
     ) rc
     on jh."job-id" = rc."rec-id" 
WHERE jh."grp-id" = '0' and
      jh."job-status" <> 'D' and
      jh."job-no" = '81088';

请注意,我使用显式连接语法替换了隐式连接语法。显式版本要好得多,所以你应该学会使用它。