我的数据库中有以下表格:
表名:保险表
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对于如何编写此查询,我将不胜感激。
发布于 2018-01-20 11:01:07
您可以使用exists
select t.*
from insurancetable t
where exists (select 1 from insurancetable t2 where t2.policy = t.policy and t2.id <> t.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)
);发布于 2018-01-20 12:40:00
我想这解决了你的问题。
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 idmin( id ),用于在出现重复时获取第一个id。例如Id % 1和Id % 8。它将只获得Id %1。
https://stackoverflow.com/questions/48352168
复制相似问题