Postgresql

如何使用 select 語句插入記錄?

  • July 5, 2020

嗨,我正在做一個項目,我正在嘗試的是,我想將使用 select 語句得到的記錄插入到臨時表中。但它給我帶來了錯誤,任何人都可以幫我解決這個問題嗎?

錯誤:關係“temp_mytbl”不存在 SQL 狀態:42P01

以下是我的查詢

truncate table temp_mytbl;
create temporary table temp_mytbl as
select iex_id,dte,agent_name,schd_total
FROM source_xrx_iex6_sandy_1.iex6_agent_adh_sum  limit 0;

insert into temp_mytbl
select iex_id,dte,agent_name,schd_total
FROM source_xrx_iex6_sandy_1.iex6_agent_adh_sum 
group by iex_id,dte,agent_name,schd_total;

SELECT i.dte,
   idm.empl_id,
   1 AS entity_id,
   sum(i.schd_total) AS s_schdhours
  FROM temp_mytbl i
    JOIN source_odw_usac.t_incontact_agentstatelog a ON a.winid = i.iex_id::text
    JOIN reporting_prod.idm_dte idm ON idm.src_id = a.agent_no AND idm.src_type_id = 618 AND soar_date(a.calendar_date_key) >= idm.start_dte AND soar_date(a.calendar_date_key) <= COALESCE(idm.end_dte, now()::date)
 GROUP BY i.dte, idm.empl_id limit 100;
WITH temp_mytbl AS ( -- without aggregation in output expression / HAVING clause
                    -- GROUP BY must be replaced with DISTINCT
                    -- which is less expensive
                    SELECT DISTINCT iex_id, dte, agent_name, schd_total
                    FROM source_xrx_iex6_sandy_1.iex6_agent_adh_sum 
                  )
SELECT i.dte, idm.empl_id, 1 AS entity_id, SUM(i.schd_total) AS s_schdhours
FROM temp_mytbl i
JOIN source_odw_usac.t_incontact_agentstatelog a ON a.winid = i.iex_id::text
JOIN reporting_prod.idm_dte idm ON idm.src_id = a.agent_no 
                              AND idm.src_type_id = 618 
                              AND soar_date(a.calendar_date_key) >= idm.start_dte 
                              AND soar_date(a.calendar_date_key) <= COALESCE(idm.end_dte, now()::date)
GROUP BY i.dte, idm.empl_id /* , entity_id */ 
-- LIMIT without ORDER BY makes no sense
ORDER BY i.dte /* or another sorting expression */
LIMIT 100;

或子查詢形式相同

SELECT i.dte, idm.empl_id, 1 AS entity_id, SUM(i.schd_total) AS s_schdhours
FROM ( SELECT DISTINCT iex_id, dte, agent_name, schd_total
      FROM source_xrx_iex6_sandy_1.iex6_agent_adh_sum 
    ) i
JOIN source_odw_usac.t_incontact_agentstatelog a ON a.winid = i.iex_id::text
JOIN reporting_prod.idm_dte idm ON idm.src_id = a.agent_no 
                              AND idm.src_type_id = 618 
                              AND soar_date(a.calendar_date_key) >= idm.start_dte 
                              AND soar_date(a.calendar_date_key) <= COALESCE(idm.end_dte, now()::date)
GROUP BY i.dte, idm.empl_id 
ORDER BY i.dte
LIMIT 100;

引用自:https://dba.stackexchange.com/questions/270318