有一张表 A 如下
id title username userid
1 中国人民 abc 11
2 中国北京 abc 11
3 美国纽约 ty 12
4 美国人 ty 12
5 英国人 pb 13
6 中国广东 pb 13
7 中国上海 mm 14我现在是想查询得到的结果是: title 中包含“中国” 并且 根据 username 去重复,同一个 username 只保留一条记录并且SQL语句已经固定格式:select * from A where ........ order by id desc
上面语句的省略号部分该怎么写?
id title username userid
1 中国人民 abc 11
2 中国北京 abc 11
3 美国纽约 ty 12
4 美国人 ty 12
5 英国人 pb 13
6 中国广东 pb 13
7 中国上海 mm 14我现在是想查询得到的结果是: title 中包含“中国” 并且 根据 username 去重复,同一个 username 只保留一条记录并且SQL语句已经固定格式:select * from A where ........ order by id desc
上面语句的省略号部分该怎么写?
from ta t
where not exists(select 1 from ta where username=t.username and id>t.id)
and charindex(N'中国',title)>0
drop table tb
Go
Create table tb([id] int,[title] nvarchar(4),[username] nvarchar(3),[userid] int)
Insert tb
select 1,N'中国人民',N'abc',11 union all
select 2,N'中国北京',N'abc',11 union all
select 3,N'美国纽约',N'ty',12 union all
select 4,N'美国人',N'ty',12 union all
select 5,N'英国人',N'pb',13 union all
select 6,N'中国广东',N'pb',13 union all
select 7,N'中国上海',N'mm',14
Go
select *
from tb t
where not exists(select 1 from tb where username=t.username and id>t.id)
and charindex(N'中国',title)>0
/*
id title username userid
----------- ----- -------- -----------
2 中国北京 abc 11
6 中国广东 pb 13
7 中国上海 mm 14(3 個資料列受到影響)*/
grant exec on EcecNmae to SQlUserID
把你的视图select出来看看。
我只执行:select * from V_Ch_news c where title like '%pusher centrifuge%' 查询出来的结果有9条,但是又4条是重复的。
我只执行:select * from V_Ch_news c where not exists(select 1 from V_Ch_news where userid=c.userid and id>c.id ) 查询出来的结果是全部列出来了,并且没有重复但是两个连在一起执行的时候为什么查询的结果只有一条记录呢?
这样有多少呢?
看看本身符合条件的有多少
Create table tb([id] int,[title] nvarchar(4),[username] nvarchar(3),[userid] int)
Insert tb
select 1,N'中国人民',N'abc',11 union all
select 2,N'中国北京',N'abc',11 union all
select 3,N'美国纽约',N'ty',12 union all
select 4,N'美国人',N'ty',12 union all
select 5,N'英国人',N'pb',13 union all
select 6,N'中国广东',N'pb',13 union all
select 7,N'中国上海',N'mm',14
select * from tb where id in (select max(id) from tb WHERE title like'中国%' group by username)这样应该可以吧
select * from tb where id in (select max(id) from tb WHERE title like'中国%' group by username)order by id desc加上排序
我用了 exists 之后好像后面没有 COMPUTE 子句和 INTO 关键字啊那如果我用 exists 的话
这句该怎么修改呢?
select * from V_Ch_news c where title like '%pusher centrifuge%' and not exists(select 1 from V_Ch_news where userid=c.userid and id>c.id )