SQL Common Scripts

1. The usage of row-to-column PIVOT

CREATE table test
(id int,name nvarchar(20),quarter int,number int)
insert into test values(1,N'苹果',1,1000)
insert into test values(1,N'苹果',2,2000)
insert into test values(1,N'苹果',3,4000)
insert into test values(1,N'苹果',4,5000)
insert into test values(2,N'梨子',1,3000)
insert into test values(2,N'梨子',2,3500)
insert into test values(2,N'梨子',3,4200)
insert into test values(2,N'梨子',4,5500)
select * from test

result:

aa0e89364b9a4ad05407a3fa5e144e1e.png

select ID,NAME,
[1] as '一季度',
[2] as '二季度',
[3] as '三季度',
[4] as '四季度'
from
test
pivot
(
sum(number)
for quarter in
([1],[2],[3],[4])
)
as pvt

result:

6c2339715489dab55147aa05e5f2498c.png

2. The usage of column-to-row UNPIOVT

create table test2
(id int,name varchar(20), Q1 int, Q2 int, Q3 int, Q4 int)
insert into test2 values(1,'苹果',1000,2000,4000,5000)
insert into test2 values(2,'梨子',3000,3500,4200,5500)
select * from test2

result:

c83ef5cde6ddd5e2747e99b06e96a346.png

--列转行
select id,name,quarter,number
from
test2
unpivot
(
number
for quarter in
([Q1],[Q2],[Q3],[Q4])
)
as unpvt

result:

7fda6ec54c55821ef25a642a1da23dfe.png

3. String replacement SUBSTRING/REPLACE

SELECT REPLACE('abcdefg',SUBSTRING('abcdefg',2,4),'**')

result:

2430dcb787a8b7e463b49f6d6a16ea1b.png

SELECT REPLACE('13512345678',SUBSTRING('13512345678',4,11),'********')

result:

0a36daf22f11cfc0d9e49c758dbef957.png

SELECT REPLACE('[email protected]','1234567','******')

result:

86218eeffa88b4367fd1c7ae68c9a1cc.png

4. Query the same record HAVING in a table

If an ID can be distinguished, it can be written like this

SELECT * FROM HR.Employees

result:

a452de5347e34eb6210290c61fc011b1.png

select * from HR.Employees
where title in (
select title from HR.Employees
group by title
having count(1)>1)

result:

766f958cadb1f576cbeee03231296d07.png

By comparison, it is found that the IDs 1 and 2 are filtered out because they have only one record

If several IDs can be distinguished, you can write this

select * from HR.Employees
where title+titleofcourtesy in
(select title+titleofcourtesy
from HR.Employees
group by title,titleofcourtesy
having count(1)>1)

result:

e52f77bd679b2428a30763dc62e35ad5.png

After the title is spliced ​​with titleofcourtesy, only those with IDs 6, 7, 8, and 9 are eligible.

5. Turn multi-row SQL data into a multi-column data, that is, add a new column

SELECT 
 id,
 name,
 SUM(CASE WHEN quarter=1 THEN number ELSE 0 END) '一季度',
 SUM(CASE WHEN quarter=2 THEN number ELSE 0 END) '二季度',
 SUM(CASE WHEN quarter=3 THEN number ELSE 0 END) '三季度',
 SUM(CASE WHEN quarter=4 THEN number ELSE 0 END) '四季度'
FROM test
GROUP BY id,name

result:

4380a836349805bd0223a27d3294af89.png

We increased the original 4 columns to 6 columns. Careful friends may have found that this result is exactly the same as the above row and column? In fact, the above line-to-column is omitted, which is a more common way of writing. 

6. Table replication

语法1:Insert INTO table(field1,field2,...) values(value1,value2,...)

语法2:Insert into Table2(field1,field2,...) select value1,value2,... from 

Table1

(Requires that the target table Table2 must exist. Since the target table Table2 already exists, we can insert constants in addition to the fields of the source table Table1.)

语法3:SELECT vale1, value2 into Table2 from Table1

(Requires that the target table Table2 does not exist, because the table Table2 will be automatically created when inserting, and the specified field data in Table1 will be copied to Table2.)

Syntax 4: Use the import and export functions for full table replication. If I use [Write a query to specify the data to transfer], then there will be problems with replication in large data tables? Because the copy will stop moving to a certain extent, and the memory will explode? It is also not written to the table. And using the above three syntaxes to execute directly will be refreshed to the database table immediately, you will know if you refresh the mdf file.

7. Use the Update statement with associated subquery to update data

--方法1:
Update Table1
set c = (select c from Table2 where a = Table1.a)
where c is null 

--方法2:
update  A
set  newqiantity=B.qiantity
from  A,B
where  A.bnum=B.bnum

--方法3:
update
(select A.bnum ,A.newqiantity,B.qiantity from A
left join B on A.bnum=B.bnum) AS C
set C.newqiantity = C.qiantity
where C.bnum ='001'

8. Connect to the remote server

--方法1:
select *  from openrowset(
'SQLOLEDB',
'server=192.168.0.1;uid=sa;pwd=password',
'SELECT * FROM dbo.test')

--方法2:
select *  from openrowset(
'SQLOLEDB',
'192.168.0.1';
'sa';
'password',
'SELECT * FROM dbo.test')

Of course, you can also refer to the previous example to establish a DBLINK for remote connection

9. Date and Time style CONVERT

The CONVERT() function is a generic function for converting dates to new data types.

The CONVERT() function can display date/time data in different formats.

grammar

CONVERT(data_type(length),data_to_be_converted,style)

data_type(length) specifies the target data type (with an optional length). data_to_be_converted contains the value that needs to be converted. style specifies the output format of the date/time.

Possible style values:

Style ID Style format
100 or 0 mon dd yyyy hh:miAM (or PM)
101 mm/dd/yy
102 yy.mm.dd
103 dd/mm/yy
104 dd.mm.yy
105 dd-mm-yy
106 dd mon yy
107 Mon dd, yy
108 hh:mm:ss
109 or 9 mon dd yyyy hh:mi:ss:mmmAM (or PM)
110 mm-dd-yy
111 yy/mm/dd
112 yymmdd
113 or 13 dd mon yyyy hh:mm:ss:mmm(24h)
114 hh:mi:ss:mmm(24h)
120 or 20 yyyy-mm-dd hh:mi:ss(24h)
121 or 21 yyyy-mm-dd hh:mi:ss.mmm(24h)
126 yyyy-mm-ddThh:mm:ss.mmm (no spaces)
130 dd mon yyyy hh:mi:ss:mmmAM
131 dd/mm/yy hh:mi:ss:mmmAM
SELECT CONVERT(varchar(100), GETDATE(), 0)
--结果:
12  7 2020  9:33PM
SELECT CONVERT(varchar(100), GETDATE(), 1)
--结果:
12/07/20
SELECT CONVERT(varchar(100), GETDATE(), 2)
--结果:
20.12.07
SELECT CONVERT(varchar(100), GETDATE(), 3)
--结果:
07/12/20
SELECT CONVERT(varchar(100), GETDATE(), 4)
--结果:
07.12.20
SELECT CONVERT(varchar(100), GETDATE(), 5)
--结果:
07-12-20
SELECT CONVERT(varchar(100), GETDATE(), 6)
--结果:
07 12 20
SELECT CONVERT(varchar(100), GETDATE(), 7)
--结果:
12 07, 20
SELECT CONVERT(varchar(100), GETDATE(), 8)
--结果:
21:33:18
SELECT CONVERT(varchar(100), GETDATE(), 9)
--结果:
12  7 2020  9:33:18:780PM
SELECT CONVERT(varchar(100), GETDATE(), 10)
--结果:
12-07-20
SELECT CONVERT(varchar(100), GETDATE(), 11)
--结果:
20/12/07
SELECT CONVERT(varchar(100), GETDATE(), 12)
--结果:
201207
SELECT CONVERT(varchar(100), GETDATE(), 13)
--结果:
07 12 2020 21:33:18:780
SELECT CONVERT(varchar(100), GETDATE(), 14)
--结果:
21:33:18:780
SELECT CONVERT(varchar(100), GETDATE(), 20)
--结果:
2020-12-07 21:33:18
SELECT CONVERT(varchar(100), GETDATE(), 21)
--结果:
2020-12-07 21:33:18.780
SELECT CONVERT(varchar(100), GETDATE(), 22)
--结果:
12/07/20  9:33:18 PM
SELECT CONVERT(varchar(100), GETDATE(), 23)
--结果:
2020-12-07
SELECT CONVERT(varchar(100), GETDATE(), 24)
--结果:
21:33:18
SELECT CONVERT(varchar(100), GETDATE(), 25)
--结果:
2020-12-07 21:33:18.780
SELECT CONVERT(varchar(100), GETDATE(), 100)
--结果:
12  7 2020  9:33PM
SELECT CONVERT(varchar(100), GETDATE(), 101)
--结果:
12/07/2020
SELECT CONVERT(varchar(100), GETDATE(), 102)
--结果:
2020.12.07
SELECT CONVERT(varchar(100), GETDATE(), 103)
--结果:
07/12/2020
SELECT CONVERT(varchar(100), GETDATE(), 104)
--结果:
07.12.2020
SELECT CONVERT(varchar(100), GETDATE(), 105)
--结果:
07-12-2020
SELECT CONVERT(varchar(100), GETDATE(), 106)
--结果:
07 12 2020
SELECT CONVERT(varchar(100), GETDATE(), 107)
--结果:
12 07, 2020
SELECT CONVERT(varchar(100), GETDATE(), 108)
--结果:
21:33:18
SELECT CONVERT(varchar(100), GETDATE(), 109)
--结果:
12  7 2020  9:33:18:780PM
SELECT CONVERT(varchar(100), GETDATE(), 110)
--结果:
12-07-2020
SELECT CONVERT(varchar(100), GETDATE(), 111)
--结果:
2020/12/07
SELECT CONVERT(varchar(100), GETDATE(), 112)
--结果:
20201207
SELECT CONVERT(varchar(100), GETDATE(), 113)
--结果:
07 12 2020 21:33:18:780
SELECT CONVERT(varchar(100), GETDATE(), 114)
--结果:
21:33:18:780
SELECT CONVERT(varchar(100), GETDATE(), 120)
--结果:
2020-12-07 21:33:18
SELECT CONVERT(varchar(100), GETDATE(), 121)
--结果:
2020-12-07 21:33:18.780

10. Division in SQL

method one

--SQL中的相除
SELECT 
CASE WHEN ISNULL(A-B,0)=0 THEN ''
ELSE CAST(CONVERT(DECIMAL(18,2),A*100.0/(A-B)) AS VARCHAR(10))+'%'  
END AS '百分数'  --FROM 表

Here we first need to determine whether the dividend is 0. If it is 0, we will give a result that we want to output. Here we return blank (it is a character type, not NULL). When it is not 0, we will give a specific calculation formula, and then convert into a character type and then spliced ​​with "%". E.g:

SELECT 
CASE WHEN ISNULL(5-2,0)=0 THEN ''
ELSE CAST(CONVERT(DECIMAL(18,2),5*100.0/(5-2)) AS VARCHAR(10))+'%'  
END AS '百分数'  --FROM 表

Returned result:

a7f77f0f54dd631e5f79724f36724f6d.png

Method Two

SELECT 
(CONVERT(VARCHAR(20),ROUND(41*100.0/88,3))+'%') AS '百分比' 
--FROM A

Results of the:

3b852328765cdba4618541f9a7f1ccc6.png

11. Rounding the ROUND function

ROUND ( numeric_expression , length [ ,function ] )
function must be tinyint, smallint, or int.
If function is omitted or its value is 0 (the default), the numeric_expression will be rounded.
If a value other than 0 is specified, the numeric_expression will be truncated.

SELECT ROUND(150.45648, 2);
--保留小数点后两位,需要四舍五入
--结果:
150.46000

SELECT ROUND(150.45648, 2, 0);
--保留小数点后两位,0为默认值,表示进行四舍五入
--结果:
150.46000

SELECT ROUND(150.45648, 2, 1);
--保留小数点后两位,不需要四舍五入,这里除0以外都是有同样的效果,
--与Oracle的TRUNC函数效果相同
--结果:
150.45000

SELECT ROUND(150.45648, 2, 2);
--保留小数点后两位,不需要四舍五入,这里除0以外都是有同样的效果,
--与Oracle的TRUNC函数效果相同
--结果:
150.45000

12. Handling of NULL values ​​in fields

method one

--CASE
SELECT 
CASE WHEN  '字段名' IS NULL THEN 'NULL' 
ELSE CONVERT(VARCHAR(20),'字段名1') END 
AS 'NewName'
--结果:
字段名1

SELECT CASE WHEN NULL IS NULL THEN 'N' 
ELSE CONVERT(VARCHAR(20),NULL) END 
AS 'NewName'
--结果:
N

Method Two

--SQL Server 2005:COALESCE
SELECT COALESCE('字符串类型字段','N') AS 'NewName'
--结果:
字符串类型字段

SELECT COALESCE(CONVERT(VARCHAR(20),'非字符串类型字段'),'N') AS 'NewName'
--结果:
非字符串类型字段

SELECT COALESCE(CONVERT(VARCHAR(20),NULL),'N') AS 'NewName'
--结果:
N

--COALESCE,返回其参数中的第一个非空表达式
SELECT COALESCE(NULL,NULL,1,2,NULL)
--结果:
1

SELECT COALESCE(NULL,11,12,13,NULL)
--结果:
11

SELECT COALESCE(111,112,113,114,NULL)
--结果:
111

13. Several cases of COUNT

--以下三种方法均可统计出表的记录数
--第一种
select count(*) from tablename

--第二种
select count(ID) from tablename

--第三种,1换成其它值也是可以的
select count(1) from tablename

14. UNION ALL multi-table insertion

Insert two tables of the same structure into a new table after union.
Of course, more than two tables of the same structure are also possible.
The same here refers to the number of columns of two or more tables and the type of each corresponding column. same,
column names can be different

select *
into table_new
from table_1
union all
select * from table_2

15. View the SQL cached in the database

use master
declare @dbid int
Select @dbid = dbid from sysdatabases
where name = 'SQL_ROAD'--修改成数据库的名称

select
dbid,UseCounts ,RefCounts,CacheObjtype,ObjType,
DB_Name(dbid) as DatabaseName,SQL
from syscacheobjects
where dbid=@dbid
order by dbid,useCounts desc,objtype

We can see what SQL is currently running in the database

16. Delete the plan cache

--删除整个数据库的计划缓存
DBCC FREEPROCCACHE

--删除某个数据库的计划缓存
USE master
DECLARE @dbid INT
SELECT @dbid=dbid FROM sysdatabases WHERE NAME = 'SQL_ROAD'
DBCC FLUSHPROCINDB (@dbid)

17. SQL line break

SQL line feed
tab CHAR(9)
line feed CHAR(10)
carriage return CHAR(13)

PRINT 'SQL'+CHAR(13)+'ROAD'
PRINT 'SQL'+CHAR(10)+'ROAD'
PRINT 'SQL'+CHAR(9)+'ROAD'

Results of the:

9c6b671323b546b736c63df65bf2609a.png

If the query results are displayed in text format instead of grid format, the SELECT statement is also applicable, we first change the query results to display in text format

3b0bbc52eeafc526237f689d13a84784.png

--以文本格式显示结果
SELECT 'SQL'+ CHAR(10)+'ROAD'
SELECT 'SQL'+ CHAR(13)+'ROAD'
SELECT 'SQL' + CHAR(10) + CHAR(13) + 'ROAD'

The result is as follows:

519971e20a75e930fa3bcf7ed64e8994.png

18、TRUNCATE 与 DELETE

TRUNCATE is a statement in SQL that deletes the contents of a data table. The usage is:

TRUNCATE TABLE [Table Name] is fast and efficient because: 
TRUNCATE TABLE is functionally identical to the DELETE statement without the WHERE clause: both delete all rows in the table. But TRUNCATE TABLE is faster than DELETE and uses less system and transaction log resources. 


The DELETE statement deletes one row at a time and records an entry in the transaction log for each row deleted. TRUNCATE TABLE deletes data by freeing the data pages used to store the table data, and only records the freeing of pages in the transaction log.

 
TRUNCATE TABLE deletes all rows in the table, but leaves the table structure and its columns, constraints, indexes, etc. unchanged. The count value used for new row identification is reset to the seed for this column.

If you want to preserve the identity count value, use DELETE instead.

If you want to drop the table definition and its data, use the DROP TABLE statement.

 
For tables referenced by FOREIGN KEY constraints, TRUNCATE TABLE cannot be used, but a DELETE statement without a WHERE clause. Since TRUNCATE TABLE is not logged, it cannot activate triggers. TRUNCATE TABLE cannot be used on tables participating in indexed views. 

19. Common system detection scripts

--查看内存状态
dbcc memorystatus

--查看哪个引起的阻塞,blk
EXEC sp_who active

--查看锁住了那个资源id,objid
EXEC sp_lock

There is also how to view the SPID of the query analyzer, which can be seen in the status bar of the query analyzer, such as sa(57), which means that the current query analyzer SPID is 57, so that the current form can be specified when using the profile. monitor. The status bar is in the lower right corner of the query window.

b0aee704af8e79ca908eb71d7e77114b.png

20. Get the execution time of the script

declare @timediff datetime
select @timediff=getdate()
select * from Suppliers
print '耗时:'+ convert(varchar(10),datediff(ms,@timediff,getdate()))

The result is as follows:

dfdce53e4df5658d46c1edebca3eadf0.png

The status bar is not accurate to milliseconds, it can only be accurate to seconds

332cb8700c40d85ec089cce1b630bca7.png

This script can more effectively view the execution efficiency of the SQL code.

Source: Data warehouse treasure library 

https://mp.weixin.qq.com/s/V4WkmA_A_Y8xUrrkuvl0sg

推荐阅读:
入门: 最全的零基础学Python的问题  | 零基础学了8个月的Python  | 实战项目 |学Python就是这条捷径
干货:爬取豆瓣短评,电影《后来的我们》 | 38年NBA最佳球员分析 |   从万众期待到口碑扑街!唐探3令人失望  | 笑看新倚天屠龙记 | 灯谜答题王 |用Python做个海量小姐姐素描图 |碟中谍这么火,我用机器学习做个迷你推荐系统电影
趣味:弹球游戏  | 九宫格  | 漂亮的花 | 两百行Python《天天酷跑》游戏!
AI: 会做诗的机器人 | 给图片上色 | 预测收入 | 碟中谍这么火,我用机器学习做个迷你推荐系统电影
小工具: Pdf转Word,轻松搞定表格和水印! | 一键把html网页保存为pdf!|  再见PDF提取收费! | 用90行代码打造最强PDF转换器,word、PPT、excel、markdown、html一键转换 | 制作一款钉钉低价机票提示器! |60行代码做了一个语音壁纸切换器天天看小姐姐!|

The year's hottest copy

Click to read the original text to see 200 Python cases!

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326956813&siteId=291194637