[英]Compare two rows in the same table for equality of one column and inequality of another column combination in SQL
我的數據庫中有下表:
表名稱:INSURANCE TABLE
ID | Policy | Lon | Lat
1 | 34564 | 2.0 | 4.0
2 | 67548 | 1.1 | 1.4
3 | 34564 | 1.8 | 9.4
4 | 98271 | 4.3 | 2.3
5 | 90198 | 5.6 | 4.5
6 | 98271 | 1.3 | 5.6
7 | 90198 | 5.6 | 4.5
8 | 34564 | 2.0 | 4.0
我正在尋找一個sql查詢,該查詢將以以下方式返回結果集:結果集包含那些行的Policy值至少等於另一行,但是(Lon,Lat)組合的另一行的值應不一樣
對於上表,我應該獲得以下結果集:
1 | 34564 | 2.0 | 4.0
3 | 34564 | 1.8 | 9.4
4 | 98271 | 4.3 | 2.3
6 | 98271 | 1.3 | 5.6
我希望能收到有關如何編寫此查詢的答復。
您可以使用exists
:
select t.*
from insurancetable t
where exists (select 1 from insurancetable t2 where t2.policy = t.policy and t2.id <> t.id);
編輯:
根據您的問題,ID應該很好。 但是,如果願意,可以使用lat和long:
select t.*
from insurancetable t
where exists (select 1
from insurancetable t2
where t2.policy = t.policy and
(t2.lat <> t.lat or t2.lon <> t.lon)
);
我認為這可以解決您的問題。
select min(t1.id) as id, t1.Policy, t1.lon, t1.lat from INSURANCE t1
inner join INSURANCE t2 on
t1.Policy = t2.Policy and t1.Id <> t2.Id
where t1.lat <> t2.lat or t1.lon <> t2.lon
group by t1.Policy, t1.lon, t1.lat
order by id
min(id)以獲取重復的第一個id。 例如ID 1和ID8。它將僅獲得ID 1。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.