注册 登录
编程论坛 SQL Server论坛

[求助]SQL过滤重复记录

caor1987 发布于 2007-05-30 15:55, 1833 次点击
我有一张表Work 里面有W_id,U_id,W_name,W_type,W_text5个字段,
表中有重复的记录如下:
W_id U_id W_name W_type W_text
1 1 哈哈 男装 rgrg
2 2 呵呵 男装 regre
3 2 西西 男装 tret
4 3 嘿嘿 男装 tretret
请问怎样才能过滤掉U_id中重复的记录得到如下的结果
1 1 哈哈 男装 rgrg
3 2 西西 男装 tret
4 3 嘿嘿 男装 tretret
我是这样写的:select *,distinct U_id from Work group by W_id 这样错了。

请教高人。。
4 回复
#2
棉花糖ONE2007-05-30 16:45
select * from work w where not exists (select 1 from work where u_id=w.u_id and w_id>w.w_id)
#3
caor19872007-05-31 11:11
厉害!!
#4
爱人2007-05-31 11:32

我的表是ID,省份,城市
ID,省份,城市
1 安徽 淮南
2 安徽 合肥
3 浙江 绍兴
想得到的结果:

安徽 淮南
合肥
浙江 绍兴
又怎么写呢>??

#5
mingwangxing2007-05-31 23:55

declare @SF char(10) --取得省份
declare @SF2 char(10) --与上次查询的省份的比较值
declare @cs char(10) --取得城市
declare myCur cursor for
select 省份,城市 from 表名 order by 省份

select @SF2 =''

open myCur

fetch myCur into @SF,@CS

while (@@fetch_status=0)
begin
if @SF2 <> @SF
print @SF + @CS
else
print ' ' + @CS
select @SF2=@SF
fetch myCur into @SF,@CS
end

close myCur

deallocate myCur

1