Left join with distinct 并计算列值
Left join with distinct and calculate column value
我有两个类似的表,我想加入它们并得到如下所示的结果
Table 1
JobNO | JobMovRefNo
---------------------------------
123 | 1
456 | 1
789 | 1
Table 2
JobNO | Arrived
---------------------------------
123 | y
123 | y
123 | n
456 | y
456 | y
结果Table
JobNO | Arrived
---------------------------------
123 | n
456 | y
789 | n
我尝试使用 group by 进行左连接,但我得到了重复的记录。非常感谢任何帮助。
提前致谢。
使用 left join
并在加入前聚合
select *
from table1 t1 left join
(select jobno, min(arrived) as arrived
from table2 t2
group by jobno
) t2
using (jobno);
你没有解释你的逻辑,但你似乎想要每行的最小值 arrived
,这就是它的作用。
编辑:
非常旧的 DB2 版本不支持 USING
。这也可以写成:
select t1.*, coalesce(t2.arrived, 'n') as arrived
from table1 t1 left join
(select jobno, min(arrived) as arrived
from table2 t2
group by jobno
) t2
on t2.jobno = t1.jobno;
做一个LEFT JOIN
,GROUP BY
。使用 coalesce
获取 'n' 表 2 中不存在的作业编号。
select t1.jobno, coalesce(min(t2.arrived), 'n')
from table1 t1
left join table2 t2 on t1.jobno = t2.jobno
group by t1.jobno
这是我的解决方案。
我使用了 postgreSQL;希望它适用于您的 dbms。
select
t1.jobno,
min(CASE WHEN t2.arrived IS NULL THEN 'n' ELSE t2.arrived END) as arrived
from table1 t1 left join table2 t2 on t1.jobno = t2.jobno
group by t1.jobno
order by t1.jobno
我有两个类似的表,我想加入它们并得到如下所示的结果
Table 1
JobNO | JobMovRefNo
---------------------------------
123 | 1
456 | 1
789 | 1
Table 2
JobNO | Arrived
---------------------------------
123 | y
123 | y
123 | n
456 | y
456 | y
结果Table
JobNO | Arrived
---------------------------------
123 | n
456 | y
789 | n
我尝试使用 group by 进行左连接,但我得到了重复的记录。非常感谢任何帮助。
提前致谢。
使用 left join
并在加入前聚合
select *
from table1 t1 left join
(select jobno, min(arrived) as arrived
from table2 t2
group by jobno
) t2
using (jobno);
你没有解释你的逻辑,但你似乎想要每行的最小值 arrived
,这就是它的作用。
编辑:
非常旧的 DB2 版本不支持 USING
。这也可以写成:
select t1.*, coalesce(t2.arrived, 'n') as arrived
from table1 t1 left join
(select jobno, min(arrived) as arrived
from table2 t2
group by jobno
) t2
on t2.jobno = t1.jobno;
做一个LEFT JOIN
,GROUP BY
。使用 coalesce
获取 'n' 表 2 中不存在的作业编号。
select t1.jobno, coalesce(min(t2.arrived), 'n')
from table1 t1
left join table2 t2 on t1.jobno = t2.jobno
group by t1.jobno
这是我的解决方案。 我使用了 postgreSQL;希望它适用于您的 dbms。
select
t1.jobno,
min(CASE WHEN t2.arrived IS NULL THEN 'n' ELSE t2.arrived END) as arrived
from table1 t1 left join table2 t2 on t1.jobno = t2.jobno
group by t1.jobno
order by t1.jobno