内部联接更新在db2中不起作用

时间:2019-01-23 05:44:04

标签: sql db2

我的结构类似于mysql中的工作查询,该结构是基于带有计数的内部联接的更新

update schema.daily_totals ct
  inner JOIN (
    SELECT
        COUNT (*) AS contacted,
        SUM( CASE WHEN f.follow_up_date BETWEEN CURRENT_DATE AND CURRENT_DATE + 7 DAYS THEN 1 ELSE 0 END ) AS potentials,
        CAST (ROUND((SUM( CASE WHEN f.follow_up_date BETWEEN CURRENT_DATE AND CURRENT_DATE + 7 DAYS THEN 1.0 ELSE 0 END )/ COUNT (*)) * 100.00, 2) AS DECIMAL (12, 2)) AS PERCENT,
        u.user_id as userID,

    FROM schema.users u
      INNER JOIN schema.notated n
        ON n.user_identifier = u.user_id
      INNER JOIN schema.comms m
        ON n.comms_ID = m.comms_ID
      LEFT JOIN schema.FDates f
        ON f.dNumber = n.dNumber
    WHERE code <> 'none'
    AND n.created_at >= CURRENT_DATE - 1 DAYS
    GROUP BY u.user_id, u.first_name, u.last_name
  ) as cu

  on cu.userID = ct.ext_id
  set ct.contacted_contacted = cu.contacted,
  ct.percent_up_to_date = cu.percent
  where ct.date_of_report >= current_date;

但是它不会运行,它似乎绕开了我要加入子查询的最后一个“ on”。

我根本无法在db2中运行它吗?

1 个答案:

答案 0 :(得分:2)

改为使用MERGE语句。

MERGE INTO schema.daily_totals ct
  USING (
    SELECT
        COUNT (*) AS contacted,
        SUM( CASE WHEN f.follow_up_date BETWEEN CURRENT_DATE AND CURRENT_DATE + 7 DAYS THEN 1 ELSE 0 END ) AS potentials,
        CAST (ROUND((SUM( CASE WHEN f.follow_up_date BETWEEN CURRENT_DATE AND CURRENT_DATE + 7 DAYS THEN 1.0 ELSE 0 END )/ COUNT (*)) * 100.00, 2) AS DECIMAL (12, 2)) AS PERCENT,
        u.user_id as userID,

    FROM schema.users u
      INNER JOIN schema.notated n
        ON n.user_identifier = u.user_id
      INNER JOIN schema.comms m
        ON n.comms_ID = m.comms_ID
      LEFT JOIN schema.FDates f
        ON f.dNumber = n.dNumber
    WHERE code <> 'none'
    AND n.created_at >= CURRENT_DATE - 1 DAYS
    GROUP BY u.user_id, u.first_name, u.last_name
  ) as cu

  on cu.userID = ct.ext_id and ct.date_of_report >= current_date
  WHEN MATCHED THEN UPDATE
  set contacted_contacted = cu.contacted, percent_up_to_date = cu.percent;