1

考虑具有以下架构的表:

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, 
4

4 回答 4

3

使用分析函数删除重复项。以下代码生成基于 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
)
于 2012-06-27T16:18:09.147 回答
1

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

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
于 2012-06-27T16:18:31.957 回答
0

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

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 列表。

于 2012-06-27T16:06:04.863 回答
-1

我认为这可以帮助你:

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

于 2012-06-27T15:57:40.483 回答