常見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 的行。






發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章