db2 基于行值的条件联接

o4hqfura  于 2022-11-07  发布在  DB2
关注(0)|答案(3)|浏览(186)

我有部门Map表,其中我有特定部门的特定状态,但所有其他部门的不同状态,不在部门表。
部门表:
| 乡村|部门|状态|
| - -|- -|- -|
| 财务部|第一天|C类|
| 财务部|第二天|C类|
| 财务部|第二次会议|O型|
| 软件工程师|第一天|C类|
动作表:
| 乡村|部门|总数|
| - -|- -|- -|
| 财务部|第一天|十六岁|
| 财务部|第三日|四十五|
| 软件工程师|第一天|十三个|
预期结果:
| 乡村|部门|总数|状态|
| - -|- -|- -|- -|
| 财务部|第一天|十六岁|C类|
| 财务部|第三日|四十五|O型|
| 软件工程师|第一天|十三个|C类|
我有这个,但它会导致重复的行(因为连接和非行):

SELECT t1.country, t1.department, t1.amt, t2.status
FROM act_table t1 
  LEFT OUTER JOIN dep_table t2
     ON t1.country = t2.country 
     AND CASE WHEN t1.department = t2.department THEN 1 WHEN t2.department = '**' THEN 1 END = 1
  • (这是一个非常简单的方案-需要以这种方式完成。)*
bxgwgixi

bxgwgixi1#

如果我没有理解错的话,如果有任何状态是'O',则需要'O'。如果只有两种状态,则可以使用相关子查询:

select a.*,
       (select d.status
        from dep_table d
        where d.country = a.country 
        order by d.status desc
        fetch first 1 row only
       ) as status
from act_table a;
but5z9lq

but5z9lq2#

我认为两个左联接使它更清楚:

with
dep_table (country, department, status) as (
  values
  ('FIN', 'D1', 'C'),
  ('FIN', 'D2', 'C'),
  ('FIN', '**', 'O'),
  ('SWE', 'D1', 'C')
),
act_table (country, department, amt) as (
  values
  ('FIN', 'D2', 16),
  ('FIN', 'D3', 45),
  ('SWE', 'D1', 13)
)
select
  act.country, act.department, act.amt, coalesce(specific.status, rest.status) status
from act_table act
  left join dep_table specific using(country, department)
  left join dep_table rest on specific.status is null and (rest.country, rest.department) = (act.country, '**')
order by country, department
jdzmm42g

jdzmm42g3#

使用olap函数row_number选择第一行

select  country ,  department ,  amt ,  status
from
(
  select a.country , a.department ,
         a.amt ,  d.status , 
         row_number() over( partition by  a.country , a.department 
                    order by  case when d.department = '**' then 1 else 0 end ) as    rn1 
    from dep_table d ,
    act_table a
    where d.country = a.country
    and   ( d.department = a.department or d.department = '**' )
) x 
where rn1 = 1

相关问题