常见SQL语句


1. 重复记录:

查询重复:

select * from tb as m,(select a ,b from tb group by a, b having count(*)>1)n where m.a = n.a and m.b= n.b
select * from tb as t where exists (select 1 from tb where a=t.a and b=t.b and id<>t.id)
select * from tb where id in (select max(id) from tb group by a,b having count(*)>1 union select min(id) from tb group by a,b having count(*)>1)


删除重复:

delete t1 from tb t1 where exists(select 1 from tb t2 where t2.d is not null and t1.a =t2.a and t1.b =t2.b and t1.id<t2.id)

 

不列出重复记录:

select top 10 * from tb where id in (select min(id) from tb group by a,b)


2. 排序:

文本按特定顺序排序(全国、上海、杭州、北京、其它区域):

select distinct Area, CHARINDEX(Area,'北京,杭州,上海,全国') as AreaS from test2 order by AreaS desc

 

要求返回这样的记录:A字段各不相同,如果有多个记录的A字段相同则取B字段最小的记录

select id,a,b from(select ROW_NUMBER() over (partition by a order by b asc) as num,* from tbl) t where t.num=1


3. 时间字段:

时间间隔超过十天

select m.time ,(selecttop 1 timefrom tb n where n.time > m.time orderby time) timefrom tb mwhere datediff(dd,m.time,(selecttop 1 timefrom tb n where n.time > m.time orderby time)) >= 10

 

4. 替换某字段:

UPDATE Price SET Area = REPLACE(Area, '市', '') where Area like '%市'

5. 字段含特殊字符(百分号等)

(1)可以将通配符模式匹配字符串用作文字字符串,方法是将通配符放在括号中;

(2)使用 ESCAPE 子句的模式匹配
可搜索包含一个或多个特殊通配符的字符串。例如,customers 数据库中的 discounts 表可能存储含百分号 (%) 的折扣值。若要搜索作为字符而不是通配符的百分号,必须提供 ESCAPE 关键字和转义符。例如,一个样本数据库包含名为 comment 的列,该列含文本 30%。若要搜索在 comment 列中的任何位置包含字符串 30% 的任何行,请指定由 WHERE comment LIKE '%30!%%' ESCAPE '!' 组成的 WHERE 子句。如果不指定 ESCAPE 和转义符,SQL Server 将返回所有含字符串 30 的行。






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值