簡體   English   中英

選擇一個值然后在同一個表中選擇這個值並在SQL中進行比較

[英]Selecting a value and then select this value in the same table and compare in SQL

Customer num.           Value.       Related Customer num 
10001.                  5000.        10002
20001                   3500.        20002
10002.                  4000.        10001
20002.                  3500.        20001 

我需要找到價值不等於相關客戶價值的客戶號碼。 請幫我。

只是:

select t.*
from mytable t
where not exists (
    select 1 
    from mytable t1 
    where t1.customer_num = t.related_customer_num and t1.value <> t.value
)

這確保,如果相關客戶的記錄存在,則其值不相同。

如果您還想檢查相關客戶的記錄是否存在:

select t.*
from mytable t
inner join mytable t1 
    on  t1.customer_num = t1.related_customer_num 
    and t1.value <> t.value
select
    t1.customerNum
from 
    table t1 
left join 
    table t2 on t1.relatedCustomerNum = t2.customerNum
where 
    t1.value <> t2.value

獲取所有記錄並匹配相關記錄。 如果需要,您還可以添加更多過濾器。 例如, t1 is not null ,這將刪除沒有相關記錄的記錄

暫無
暫無

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

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