Advanced T-SQL query in SQL Server databases

First, the function used by the query

Please create your own databases and tables, insert data in the table, my example is as follows:

create database accp;    <!--创建accp数据库-->
use accp;     <!--切换到accp数据库-->
create table test (            <!--创建test表-->
    编号  int     identity(1,1) not null,
    姓名  nvarchar(4) not null,
    证件号码 varchar(18) primary key,
    职务  nvarchar(6) null,
    入职时间 datetime   null,
    出生日期 datetime null,
    基本工资 money null check (基本工资 >=0 and 基本工资 <= 10000),
);
select * from test;      <!--查看test表结构-->
alter   table test add 备注 nvarchar(50);    <!--添加一列备注列-->
     <!--表中插入数据 -->
insert into test values ('王三','111111111111111111','初级运维','2011/3/8','1980/12/3',7500,'老员工');
insert into test values ('杜五','222222222222222222','中级运维','2007/7/24','1999/9/7',8500,'老员工');
insert into test values ('丽丽','333333333333333333','高级运维','2017/1/1','1999/12/1',6500,'新员工');
insert into test values ('赵六','444444444444444444','高级运维','2016/4/18','1985/5/9',6000,'新员工');
insert into test values ('王五','555555555555555555','中级运维','2014/9/9','1994/11/21',10000,'老员工');
insert into test values ('李四','666666666666666666','初级运维','2018/4/16','1996/12/7',7500,'新员工');
insert into test values ('王朝','777777777777777777','初级运维','2015/6/3','1991/10/2',8000,'老员工');
select * from test;     <!--查看test表中数据-->

Advanced T-SQL query in SQL Server databases

1, the system function

Advanced T-SQL query in SQL Server databases
CONVERT and CAST casts frequent use, can be used on many occasions. Especially in the application site is often necessary to convert the various types of data to a string in a specified format, and then assembled into the display.

The example system functions as follows:

1) the data conversion, convert the string to an integer

select convert(varchar(5),12345) as 将字符转换为整数;

Advanced T-SQL query in SQL Server databases

2) Data conversion, converts the date datetime

select cast('2019-12-29'as datetime) as 日期和时间;

Advanced T-SQL query in SQL Server databases

3) displays the user login database

select current_user as 登录用户;
select system_user as 系统用户;

Advanced T-SQL query in SQL Server databases
Advanced T-SQL query in SQL Server databases

4) displays the name of the log on the computer

select host_name() as 登录计算机名字;

Advanced T-SQL query in SQL Server databases

5 string length) input statistics

select datalength('缘分让我们相遇!!!') as 字符串长度;

Advanced T-SQL query in SQL Server databases

6) Use account query the user's ID

select user_name(1) as 当前用户;

Advanced T-SQL query in SQL Server databases

2, String Functions

String function returns control to the user for the string, character data only for these functions. There are strings in the information processing special place, almost all information needs to be converted into a string to display properly, especially the use of stitching together different data displayed more extensive, string concatenation is very simple to use between two strings. " + "button.
Advanced T-SQL query in SQL Server databases

Example string functions as follows:

1) comparing a string position another string

select charindex('alibaba','www.alibaba.com') as 字符串比较;

Advanced T-SQL query in SQL Server databases

String length 2) Statistics input

select len ('好好学习天天向上') as 字符串长度;

Advanced T-SQL query in SQL Server databases

3) The lowercase to uppercase character string adjustment

select upper ('www.baiduyun.com') as 调整为大写;

Advanced T-SQL query in SQL Server databases

4) the seventh from the right string display

select RIGHT ('www.baiduyun.com',7);

Advanced T-SQL query in SQL Server databases

5) replace the string of characters

select replace ('ababababa','a','b') as 将a替换成b;

Advanced T-SQL query in SQL Server databases

6) Delete the specified location string into a new string, delete the fourth character and the fifth character to insert new content

select stuff ('wwwwww',4,5,'桥边姑娘');

Advanced T-SQL query in SQL Server databases

7) Use splicing operation and maintenance of the primary character display name and basic wage

select '中级运维'+姓名+'的基本工资是:'+ cast (基本工资 as varchar(20))+'元' from test where 职务='中级运维';

Advanced T-SQL query in SQL Server databases

3, date function

Date can not directly use mathematical functions in SQL Server, you need to use the date functions to manipulate date values. Date functions help extract the value of the date, month and year, respectively, in order to operate them.
Advanced T-SQL query in SQL Server databases

Example date functions as follows:

1) to obtain the current system time

select getdate() as 当前系统时间;

Advanced T-SQL query in SQL Server databases

2) add time, (YY year, MM month, DD date)

select dateadd (mm,20,'2019-5-3') as 添加时间;

Advanced T-SQL query in SQL Server databases

3) determining the difference between two time

select datediff (yy,'2019-10-1','2029-10-1') as 差;

Advanced T-SQL query in SQL Server databases

4) a specific portion of the string of modification date, week display

select datename (dw,'2020-1-3') as 星期;

Advanced T-SQL query in SQL Server databases

5) displays the date and time of

select datepart (month,'2019-1-1') as 日;

Advanced T-SQL query in SQL Server databases

6) displays the date after twenty days

select dateadd (dd,20,getdate()) as 二十天后的日期;

Advanced T-SQL query in SQL Server databases

7) test to calculate the age of the employee table Week

select 姓名,datediff (yy,出生日期,getdate()) as 年龄 from test;

Advanced T-SQL query in SQL Server databases

When entering the code, must pay attention to the problem input method, make sure the state is English input method, otherwise it will error.

4, the query packet with the aggregate functions

Conventional polymerization functions are SUM (), AVG (), MAX (), MIN () and COUNT ().

  • SUM (): SUM () function returns the sum of all numbers in the expression, it can only be used for numeric columns, other data types can not be aggregated character, date;

  • AVG (): AVG () function returns the value of the average of all expressions, they can only be used for numeric columns;

  • MAX()和MIN():MAX()函数返回表达式中的最大值,MIN()函数返回表达式中的最小值,它们都可以用于数字型、字符型及日期/时间类型的列;

  • COUNT():COUNT()函数返回表达式中非空值的技数,它可以用于数字和字符类型的列;

另外,也可以使用星号(*)作为COUNT()函数的表达式,使用星号可以不必指定特定的列而计算所有的行数;

聚合函数示例如下:

1) 计算员工信息表的总工资

select sum(基本工资) as 总工资 from test;

Advanced T-SQL query in SQL Server databases

2)计算员工平均工资

select avg(基本工资) as 平均工资 from test;

Advanced T-SQL query in SQL Server databases

3)计算最高和最低的工资

select max(基本工资) as 最高工资, min(基本工资) as 最低工资 from test;

Advanced T-SQL query in SQL Server databases

4)统计表中行数据

select COUNT(*) as 总行数 from test;

Advanced T-SQL query in SQL Server databases

分组查询示例如下:

分组查询就是将表中的数据通过GROUP BY子句分类组合,再根据需要得到统计信息。如果需要对分组结果进行筛选,只显示满足限定条件的组,需要使用HAVING子句。
不难理解,在使用GROUP BY关键字时,在SELECT列表中可以指定的项目是有限的,SELECT语句中仅允许以下几项:

  • 被分组的列;
  • 为每个分组返回一个值的表达式,如用一个列名作为参数的聚合函数;

1)分组查询表中每个职务的平均工资

select 职务,SUM(基本工资) as 职务总工资 from test group by 职务;

Advanced T-SQL query in SQL Server databases

2)分组查询表中平均工资小于13000显示出来

select 职务,SUM(基本工资) as 职务总工资 from test group by 职务 having sum(基本工资) < 13000;

Advanced T-SQL query in SQL Server databases
当GROUP BY子句中使用HAVING子句时,查询结果只返回满足HAVING条件的组。在一个T-SQL语句中可以有WHERE子句和HAVING子句,HAVING子句与WHERE子句类似,均用于设置限定条件。但HAVING子句和WHERE子句的区别如下:

  • WHERE子句的作用是在对分组查询结果进行分组之前,根据WHERE条件筛选数据,条件中不能包含聚合函数;

  • HAVING子句的作用是在分组之后筛选满足条件的组,条件中经常包含聚合函数,也可以使用多个分组标准进行分组;

5、数学函数

数学函数用于对数值进行代数运算,由于数学函数数量众多,不可能全部列举。简单列举几个如下表:
Advanced T-SQL query in SQL Server databases

数学函数示例如下:

1)显示整数

select ABS (-100) as 显示整数;
select ABS (20) as 显示整数;

Advanced T-SQL query in SQL Server databases
Advanced T-SQL query in SQL Server databases

2)取值大于,四舍五入

select CEILING (33.7) as 取值大于四舍五入;

Advanced T-SQL query in SQL Server databases

3)取值小于,四舍

select FLOOR (22.4) as 取值小于五舍去;

Advanced T-SQL query in SQL Server databases

4)计算平方或者次幂

select POWER (2,3) as 计算次幂;

Advanced T-SQL query in SQL Server databases

5)四舍五入精确数

select ROUND (50,333.2) as 四舍五入精确数;

Advanced T-SQL query in SQL Server databases

6)正数返回+1,负数返回-1,0返回0

select SIGN (-10) as 负数返负1; 
select SIGN (30) as 正数返1;
select SIGN (0) as 返回0;

Advanced T-SQL query in SQL Server databases

Advanced T-SQL query in SQL Server databases

Advanced T-SQL query in SQL Server databases

7)计算数字平均值

select SQRT (40) as 计算数字平均值;

Advanced T-SQL query in SQL Server databases

8)计算test表基本工资的平均数

select CEILING (avg (基本工资)) as 平均工资 from test;

Advanced T-SQL query in SQL Server databases

9) Statistical computing the employee's name from the 30-year-old, how many days

select 姓名,出生日期,DATEDIFF(YY,出生日期,GETDATE())
AS 年龄,DATEDIFF(DD,GETDATE(),DATEADD(yy,30,出生日期))
AS 距离30岁天数 from test
where DATEDIFF(YY,出生日期,GETDATE()) <=30 order by 出生日期;

Advanced T-SQL query in SQL Server databases

10) stitching characters display the name under the age of 30 years old, how many days

select
'员工'+姓名+
'的生日是'+CONVERT(varchar(20),出生日期,111)+
',现在年龄是'+CAST(DATEDIFF(YY,出生日期,GETDATE()) AS varchar(10))+'岁'+
',距离30岁生日还有'+
CAST (DATEDIFF(DD,GETDATE(),DATEADD(YY,30,出生日期)) AS varchar(10))+'天'
from test
where datediff (yy,出生日期,getdate()) <=30
order by 出生日期;

Advanced T-SQL query in SQL Server databases

Two, T-SQL statement multi-table queries cases

Use T-SQL to achieve a multi-table query (inner joins, left outer join, right outer joins, the whole coupling / full outer join)

1. Create A table

create table A      <!--创建A表-->
(
    姓名 nvarchar(5) not null,
    学校 nvarchar(10) not null,
);
insert into A values ('李寒','北京大学');    <!--数据插入A表-->
insert into A values ('张玉','清华大学');      <!--数据插入A表-->
insert into A values ('刘敏','中国人民大学');    <!--数据插入A表-->
insert into A values ('孙明明','浙江大学');     <!--数据插入A表-->
select * from A;     <!--查看A表数据-->

Advanced T-SQL query in SQL Server databases

2. Create a B table

create table B    <!--创建B表-->
(
    姓名 nvarchar(5) not null,
    职业 nvarchar(10) not null,
);
insert into B values ('张玉','咨询师');    <!--数据插入B表-->
insert into B values ('刘敏','作家');       <!--数据插入B表-->
insert into B values ('张明翰','建筑师');    <!--数据插入B表-->
insert into B values ('王博','工程师');          <!--数据插入B表-->
select * from B;    <!--查看B表数据-->

Advanced T-SQL query in SQL Server databases

3, an example of the coupling

A coupling implemented method 1)

  <!--在表A和表B中使用内联接查询学生姓名、学校和职业-->
select A.姓名 姓名A,A.学校 学校A,B.姓名 姓名B,B.职业 职业B
from A,B where A.姓名=B.姓名

Advanced T-SQL query in SQL Server databases

2) the two coupled-implemented method

<!--在from子句中使用inner join…on子句来实现-->
select A.姓名 姓名A,A.学校 学校A,B.姓名 姓名B,B.职业 职业B
from A inner join B on A.姓名=B.姓名

Advanced T-SQL query in SQL Server databases

4, an example of the outer coupling

1) left outer coupling

<!--左外联接,在表A和表B中使用左外联接查询学生姓名、
学校和职业-->
select A.姓名 姓名A,A.学校 学校A,B.姓名 姓名B,B.职业 职业B
from A left join B on A.姓名=B.姓名

Advanced T-SQL query in SQL Server databases

2) the right outer coupling

<!--右外联接,在表A和表B中使用右外联接查询学生姓名、
学校和职业-->
select A.姓名 姓名A,A.学校 学校A,B.姓名 姓名B,B.职业 职业B
from A right join B on A.姓名=B.姓名

Advanced T-SQL query in SQL Server databases

3) complete the outer coupling

<!--完整外联接,在表A和表B中使用完整外联接查询学生姓名、
学校和职业-->
select A.姓名 姓名A,A.学校 学校A,B.姓名 姓名B,B.职业 职业B
from A full join B on A.姓名=B.姓名

Advanced T-SQL query in SQL Server databases

Third, use the function inquiry statistics Cases

1, create tables and insert data into the database

create database bdqn;    <!--创建bdqn数据库-->
use bdqn;      <!--切换到bdqn数据库-->
create table products    <!--创建products表-->
(
    编号 int identity (1,1) primary key,
    名称 nvarchar(10) not null,
    种类 nvarchar(10) not null,
    成本 money not null check (成本 >=0 and 成本 <=60),
    出厂日期 datetime not null,
);
insert into products values      <!--products表插入数据-->
('西瓜','水果','4.1','2017/05/06'),
('芹菜','蔬菜','1.0','2017/04/01'),
('番茄','蔬菜','2.9','2017/04/01'),
('黄瓜','蔬菜','2.2','2017/05/09'),
('香蕉','水果','6.1','2017/05/23'),
('核桃','坚果','28.5','2017/06/02'),
('开心果','坚果','38.11','2017/06/21'),
('蓝莓','水果','50.2','2017/05/15');
select * from products;        <!--查看products表数据-->

Advanced T-SQL query in SQL Server databases

2, an example of the operation function

1) date of inquiry later than April 2017 fruit information

select * from products where 种类='水果' and 出厂日期>'2011-04-01';

Advanced T-SQL query in SQL Server databases

2) grouping query total cost of all fruits, vegetables, nuts

select 种类,sum (成本) as 总成本 from products group by 种类;

Advanced T-SQL query in SQL Server databases

3) query name and date of all the fruit, in a specific format concatenate strings, such as "Watermelon manufacture date is: 2017/05/06"

select '查询'+种类+'的出厂日期是:' + convert (varchar(10),出厂日期,111) from products;

Advanced T-SQL query in SQL Server databases

4) the average cost of all queries vegetables

select 种类, avg(成本) as 蔬菜的平均成本 from products group by 种类 having 种类='蔬菜';

Advanced T-SQL query in SQL Server databases

Fourth, multi-table queries cases

This case connected to a case and do! ! !

1. Create a sales table insert data

create table sales   <!--创建sales表-->
(
    名称 nvarchar(5) not null,
    销售地点 nvarchar(3) not null,
    销售价格 money not null check (销售价格 >=0 and 销售价格 <=65),
);
insert into sales values    <!--sales表中插入数据-->
('苹果','河北','5.0'),
('香蕉','湖南','6.2'),
('番茄','北京','3.15'),
('黄瓜','湖北','2.45'),
('芹菜','河北','1.11'),
('草莓','北京','10.0'),
('哈密瓜','北京','8.98'),
('蓝莓','上海','59.9'),
('核桃','海南','35.8');
select * from sales;     <!--查看sales表中数据-->

Advanced T-SQL query in SQL Server databases

2, multi-table query example

1) the name of the query product in the products table and the sales table, type, cost, selling price and sales locations

select products.名称,products.种类,
products.成本,sales.销售地点,sales.销售价格
from products inner join sales
on products.名称=sales.名称;

Advanced T-SQL query in SQL Server databases

2) query sold in Hainan product name, type, cost and selling price in the products table and the sales table

select products.名称,products.种类,
products.成本,sales.销售价格
from products inner join sales 
on products.名称=sales.名称
and sales.销售地点='海南';

Advanced T-SQL query in SQL Server databases

3) Query vegetables sold in Beijing's name, type, cost and selling price in the products table and the sales table

select products.名称,products.种类,products.成本,sales.销售价格
from products inner join sales on products.名称=sales.名称 and sales.销售地点='北京' where 种类='蔬菜';

Advanced T-SQL query in SQL Server databases

-------- end of this article so far, thanks for reading --------

Guess you like

Origin blog.51cto.com/14156658/2463653