涉及左外部联接的组列

时间:2014-03-12 16:54:26

标签: sql

我试图将所有信息数据分组/汇总在一起,但我不能让我了解它。

是因为我有内连接吗?

SELECT DISTINCT jh."job-date",jh."company", jh."job-dept", jh."job-route", rc.COSTS, rh.SALES, rh.SALES - rc.COSTS as PROFIT
FROM MSN.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 MSN.PUB."rec-cost" rc
  group by rc."rec-id") rc
 on jh."job-id" = rc."rec-id"

WHERE
  jh."job-status" <> 'D' and
  jh."job-date" between '2012-04-01' and '2013-03-31'
 Group by jh."job-route", jh."company", jh."job-dept",jh."job-date", rc."COSTS", rh."SALES"

这是我离开的结果。

工作日期公司工作部门工作路线成本销售利润

2012-04-01 03 AII IBD 793.48 820.53 27.05

2012-04-01 03 AII ICH 20.87 43.35 22.48

2012-04-01 03 AII ICH 130.97 143.64 12.67

2012-04-01 03 AII ICH 291.52 363.63 72.11

2012-04-01 03 AII ICH 384.90 437.44 52.54

我需要对它们进行总结,以便我没有这么多行数据?

1 个答案:

答案 0 :(得分:1)

您的问题是group by条款:

SELECT jh."job-date",jh."company", jh."job-dept", jh."job-route",
       sum(rc.COSTS) as COSTS,
       sum(rh.SALES) as SALES, sum(rh.SALES - rc.COSTS) as PROFIT
FROM MSN.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 MSN.PUB."rec-cost" rc
      group by rc."rec-id"
     ) rc
     on jh."job-id" = rc."rec-id"
WHERE jh."job-status" <> 'D' and
      jh."job-date" between '2012-04-01' and '2013-03-31'
Group by jh."job-route", jh."company", jh."job-dept", jh."job-date";

我从COSTS删除了SALESgroup by,并在select中添加了聚合函数。