【问题标题】:How do you remove all duplicate pairs from a list?如何从列表中删除所有重复的对?
【发布时间】:2019-11-07 11:24:56
【问题描述】:

我想添加每个 PID 的 PY 量相同的所有 CY 值

也就是说:PID 1 的 PY 和 PID 4 的 PY 是一样的。 PID 2的PY和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
    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 值?

【问题讨论】:

  • 你为什么要 ID 1 行而不是 2 或 3 行?

标签: sql sqlite duplicates unique distinct


【解决方案1】:

您可以很容易地删除第 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
                 );

根据您的描述,我认为您希望将其汇总为py

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;

但是,这不会返回您指定的结果。 Here 是一个 dbfiddle。

【讨论】:

    【解决方案2】:
    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    
    

    【讨论】:

    • 这是一个答案吗?如果没有,请编辑您的问题并将此代码放在那里,然后删除此帖子。如果是,请编辑并提及这是您问题的答案。
    猜你喜欢
    • 2011-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-28
    • 2017-08-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多