Oracle检查另一个表

时间:2015-10-16 21:26:10

标签: sql oracle join

这是我一直在努力的一个。我有一个查询按预期提取数据...

SELECT a.plant,
       SUBSTR(a.completed_ts, 1, 4) wo_year,
       a.asset_nbr asset,
       c.asset_desc descr,
       c.dept dept,
       COUNT(DISTINCT a.work_order_nbr)) freq,
       SUM(b.labor_hours) labor_hours
FROM table_a a
LEFT JOIN table_b b ON b.work_order_nbr = a.work_order_nbr
AND b.plant = a.plant,
    table_c c
WHERE a.plant = :Plant
  AND c.plant = a.plant
  AND c.asset_nbr = a.asset_nbr
  AND SUBSTR(a.completed_ts, 1, 4) = :year
GROUP BY A.PLANT,
         A.ASSET_NBR,
         C.ASSET_DESC,
         C.DEPT,
         SUBSTR(A.COMPLETED_TS, 1, 4)

我接下来需要做的是加入table_d,根据plantdepartment从上述查询返回的记录中提取费率值。

Table_d有3列... plantdepartmentrate。在table_d中,并非所有植物/部门组合都存在,甚至不存在所有植物。 table_d中的某些工厂具有空白('')部门值 - 工厂的通用费率,适用于任何其他部门。

所以为了提高利率,我需要像...这样的东西。

  • 如果在table_d中找到工厂和部门组合,请提取具体费率,
  • 如果工厂在table_d而非dept中找到,则拉动率为table_ddepartment = ' '的植物存在table_d
  • else ...如果rate中的工厂不存在...将char设置为0

有关于此的任何想法吗?

1 个答案:

答案 0 :(得分:0)

以下内容可以让您接近您正在寻找的内容:

SELECT a.plant,
       SUBSTR(a.completed_ts, 1, 4) wo_year,
       a.asset_nbr asset,
       c.asset_desc descr,
       c.dept dept,
       COALESCE(department_rate.RATE, plant_default_rate.RATE, 0) AS RATE,
       COUNT(DISTINCT a.work_order_nbr)) freq,
       SUM(b.labor_hours) labor_hours
FROM table_a a
LEFT OUTER JOIN table_b b
  ON b.work_order_nbr = a.work_order_nbr AND
     b.plant = a.plant
INNER JOIN table_c c
  ON c.plant = a.plant AND
     c.asset_nbr = a.asset_nbr
LEFT OUTER JOIN TABLE_D department_rate
  ON department_rate.PLANT = a.PLANT AND
     department_rate.DEPARTMENT = c.DEPT
LEFT OUTER JOIN (SELECT *
                   FROM TABLE_D
                   WHERE DEPARTMENT = ' ') plant_default_rate
  ON plant_default_rate.PLANT = a.PLANT
WHERE a.plant = :Plant AND 
      SUBSTR(a.completed_ts, 1, 4) = :year
GROUP BY A.PLANT,
         A.ASSET_NBR,
         C.ASSET_DESC,
         C.DEPT,
         SUBSTR(A.COMPLETED_TS, 1, 4),
         COALESCE(department_rate.RATE, plant_default_rate.RATE, 0)

祝你好运。