SQL插入到select from中-插入ID而不是数据

收藏

我需要用lds_placement表中的数据填充事实表我已经选择了这些记录,下面是它的样子:

fk1_account_id | fk3_job_role_id | salary | no_of_placements |  YEAR
---------------------------------------------------------------------
     10        |        3        | 165000 |        5         |  2010
     10        |        3        | 132000 |        4         |  2011
     10        |        3        | 132000 |        4         |  2012
     20        |        2        | 990000 |        3         |  2010
     20        |        2        | 132000 |        2         |  2011
     20        |        2        | 132000 |        2         |  2012    

我想从另一个名为time_id的表中插入time_dim到列year中,而不是实际年份本身。
time_dim表如下所示:
time_id | year
---------------
   5    | 2015
   1    | 2013
   2    | 2010
   3    | 2014
   4    | 2012
   6    | 2011

我需要在“年份”栏中插入的是:
year
 2
 6
 4
 2
 6
 4

请告诉我在表格中插入time_id而不是year的方法。
这是我用来选择最上面的表的代码。
SELECT
     fk1_account_id,
     fk3_job_role_id,
     Sum(actual_salary)                             AS salary,
     Count(1)                                       AS no_of_placements,
     MAX(EXTRACT(YEAR FROM plt_estimated_end_date)) AS year
  FROM lds_placement
 GROUP BY fk1_account_id, fk3_job_role_id, EXTRACT(YEAR FROM plt_estimated_end_date)
 ORDER BY fk1_account_id;


最佳答案:

如果想捕获left join不存在于year中的记录,请使用time_dim。否则使用inner_join

select t.fk1_account_id,t.fk3_job_role_id,t.salary,t.no_of_placements
,d.time_id 
from 
(SELECT fk1_account_id, fk3_job_role_id, Sum(actual_salary) as salary, Count(1) as no_of_placements, MAX(EXTRACT(YEAR FROM plt_estimated_end_date)) AS YEAR 
FROM lds_placement
GROUP BY fk1_account_id, fk3_job_role_id, EXTRACT(YEAR FROM plt_estimated_end_date)
)t
left join time_dim d
on t.year=d.year
order by t.fk1_account_id

回复