SQL:如果null根据表A

时间:2018-04-20 23:30:19

标签: sql oracle

想知道是否有人可以给我提示如何最好地解决此查询问题。

我有两个表可以通过福利代码和公司代码加入。只有表A有员工编号。

表A - 有员工数据及其福利金额和代码。如果为null,则查看表B以获取福利代码的默认金额。

表B - 公司的福利代码的默认金额。

以下是我想要了解的内容。只汇总了突出显示的内容。不确定最好的方法是获得我需要的结果。我尝试了多种方法。我在两者之间创建了一个联盟,我可以在外部查询上提供一些逻辑,但我再次遇到障碍。

enter image description here

Select 
*
from (
SELECT
    EMB_EMP_NO
  , EMB_COMP_CODE
  , EMB_BEN_CODE
  ,   SUM(
    CASE
      WHEN EMB_BEN_CODE IN ('9600', '9601', '9602', '9603', '9604')
      AND EMB_BEN_TYPE  = 'P' AND EMB_BEN_AMOUNT IS NOT NULL
      THEN (EMB_BEN_AMOUNT / 100)
    ELSE 0
  END) AS "53RDBURDEN_PERC" 
  FROM
    da.pyempben t3
  WHERE
    EMB_BEN_CODE   IN ('9600', '9601', '9602', '9603', '9604')
  AND EMB_END_DATE IS NULL
  AND EMB_COMP_CODE = 'ACC'
  AND EMB_EMP_NO = '8687'
  GROUP BY
    EMB_EMP_NO
  , EMB_COMP_CODE
  , EMB_BEN_CODE
union


SELECT
    'DEFAULT' AS "DEFAULT_BENCODE"
   , COB_COMP_CODE                                              AS "ACPYSALRPTC_COMPCODE"
   , COB_BEN_CODE                                               AS "ACPYSALRPTC_BENCODE"    
   ,   
    CASE
      WHEN COB_BEN_CODE IN ('9600', '9601', '9602', '9603', '9604')
      AND COB_BEN_TYPE  = 'P'
      THEN (COB_BEN_AMOUNT / 100)
    ELSE 0
  END                                                           AS "ACPYSALRPTC_53RDBURDPERC"   
  FROM
    DA.PYCOMBEN
  WHERE
    COB_BEN_CODE   IN ('9600', '9601', '9602', '9603', '9604')
  AND COB_END_DATE IS NULL
  AND COB_PRN_CODE  = 'WK'
  and cob_comp_code = 'ACC'
  ) src
 ;

enter image description here

1 个答案:

答案 0 :(得分:1)

SELECT
  a.EMB_EMP_NO                                      AS EMP_NO,
  a.EMB_COM_CODE                                    AS Comp_Code,
  a.Benefit_Name,
  SUM(COALESCE(a.Benefit_Amount, b.Default_Amount)) AS total_amount
FROM
  table_a a
JOIN
  table_b b
ON
  a.Benefit_Code = b.Benefit_Code
AND
  a.EMB_COMP_CODE = b.COB_COMPCODE
GROUP BY
  a.EMB_EMP_NO,
  a.EMB_COM_CODE,
  Benefit_Name
;

如何使用SUM(COALESCE())?祝你好运!