【问题标题】:SQL to delete duplicate records with some common field values?SQL删除一些常见字段值的重复记录?
【发布时间】:2012-06-27 15:55:14
【问题描述】:

考虑具有以下架构的表:

id, location, starred

同一位置的记录有很多:

id | location | starred
-----------------------
1     rome      yes
2     rome      no
3     rome      no
4     milan     yes
5     milan     no
6     bozen     no

我希望每个位置最多有一条记录。考虑到加星记录和未加星记录之间的选择,我想要加星。 那么什么sql会产生这个表:

id | location | starred
-----------------------
1     rome      yes
4     milan     yes
6     bozen     no

我怀疑这可以通过一些虚拟表或“视图”来完成。

DELETE FROM table
GROUP BY location, 

【问题讨论】:

  • 所以你只想在模式中选择不同的城市,如果有重复,你想要'starred' = yes?
  • 是的,也许会创建该选择查询的具体化视图。

标签: sql duplicates sql-delete mysql4


【解决方案1】:

使用分析函数删除重复项。以下代码生成基于 row_number 的位置,并按星号 desc 排序(所以先是)

 delete from mytable2 where id in ( 
select id from
( select  id, location,starred,row_number() over ( partition by location order by location, starred desc) row_num 
  from mytable2
) where row_num >1
)

【讨论】:

  • 这将特定于 MS SQL Server。然而,理想的解决方案。
【解决方案2】:

如果 [started] 只能是 yes 或 no,那么这应该有效:

create table data
(
id int identity(1,1),
location varchar(50),
[started] varchar(3)
)

insert into data select 'Rome', 'Yes'
insert into data select 'Rome', 'No'
insert into data select 'Rome', 'No'
insert into data select 'Milan', 'Yes'
insert into data select 'Milan', 'No'
insert into data select 'Bozen', 'No'

WITH locationsRanked (id, location, [started], rank)
AS
(
    select min(Id), location, [started],
    RANK() OVER (PARTITION BY location  ORDER BY location, [started] DESC) AS Rank
    from data
    group by location, [started]
)
select * from locationsRanked where Rank = 1
order by id

【讨论】:

    【解决方案3】:

    如果你只是想提取数据,这样的事情应该可以工作:

    select
        [table].*
    from
        [table]
        inner join (select 
                        MIN(id) as id, 
                        location 
                    from 
                        [table] 
                    group by location) as data
            on [table].id = data.id
    

    显然,您也可以使用此(或类似查询)的结果来确定要删除的 id 列表。

    【讨论】:

    • 您忽略了加星标的约束
    【解决方案4】:

    我认为这可以帮助你:

    http://www.w3schools.com/sql/sql_distinct.asp

    【讨论】:

      猜你喜欢
      • 2018-05-07
      • 2016-01-07
      • 1970-01-01
      • 2010-10-24
      • 2018-02-17
      • 2020-07-16
      • 2021-02-13
      • 2017-11-19
      相关资源
      最近更新 更多