Sql 如何从列表中删除所有重复对?
我想添加CY的所有值,其中PY值与每个PID相同 换句话说:PID 1的PY和PID 4的PY是相同的。 PID 2和PID 5的PY相同Sql 如何从列表中删除所有重复对?,sql,sqlite,duplicates,unique,distinct,Sql,Sqlite,Duplicates,Unique,Distinct,我想添加CY的所有值,其中PY值与每个PID相同 换句话说:PID 1的PY和PID 4的PY是相同的。 PID 2和PID 5的PY相同 Select [ID] ,a.[PY] ,a.[CY] ,a.[LAT] ,a.[LON] Into #tempa From MyTable as a INNER JOIN MyTable as b on a.PY = b.PY and a.ID <> b.ID Select Conver
Select
[ID] ,a.[PY] ,a.[CY] ,a.[LAT] ,a.[LON] Into #tempa
From MyTable as a
INNER JOIN MyTable as b on a.PY = b.PY and a.ID <> b.ID
Select
Convert (varchar, LAT) + ', ' + convert (varchar, LON) as 'Combined',
SUM(CY) as Total ,COUNT(ID) as [Count] Into #tempb
From #tempa
Group by Convert (varchar, LAT) + ', ' + convert (varchar, LON)
Having COUNT(ID) < 2
Select
SUM(Total) as [Total]
From #tempb
如何仅添加ID 1、4和5的CY值?您可以非常轻松地删除第2行和第3行:
select *
from insurance i
where not exists (select 1
from insurance i2
where i2.location_pair = i.location_pair and i2.pid <> i.pid
);
但是,这不会返回指定的结果。是一个数字小提琴。您为什么想要ID 1行而不是2或3行?这是答案吗?如果没有,请编辑您的问题并将此代码放在那里,然后删除此帖子。如果是,请编辑并注明这是您问题的答案。
select min(pid), py, sum(cy), min(location_pair)
from insurance i
where not exists (select 1
from insurance i2
where i2.location_pair = i.location_pair and i2.pid <> i.pid
)
group by py;
Select * Into #temp2 From #temp t
Where Exists (
Select 1 From #temp t2
Where i2.PY = t.PY and t2.ID <> t.ID);
Select * Into #temp3 From #temp t
Where Not exists (
Select 1 From #Temp t2
Where t2.ID <> t.ID);
Select * From #temp2
Select * From #temp3
SELECT SUM(a.CY) as CY FROM #temp2 a
INNER JOIN #temp3 b on a.ID = b.ID