簡體   English   中英

Left join with distinct 並計算列值

[英]Left join with distinct and calculate column value

我有兩個表,我想加入並得到如下所示的結果

表格1

JobNO       |       JobMovRefNo
---------------------------------
123         |   1
456         |   1
789         |   1

表 2

JobNO       |   Arrived
---------------------------------
123         |   y
123         |   y
123         |   n
456         |   y
456         |   y

結果表

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;

這是我的解決方案。 我用的是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 

做一個LEFT JOINGROUP BY 使用coalesce為表 2 中不存在的作業號獲取“n”。

select t1.jobno, coalesce(min(t2.arrived), 'n')
from table1 t1
left join table2 t2 on t1.jobno = t2.jobno
group by t1.jobno

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM