10分钟学会SQL server

文章目录

    • 1、建表
    • 2、插入数据
    • 3、数据类型
    • 4、函数
      • (1) Aggregate函数
      • (2) 文本处理函数
      • (3) 日期和时间处理函数
      • (4) 数值处理函数
      • (6) 其他函数
    • 5、增删改查
    • 附录
      • [系统掌握SQL Server增删改查](https://blog.csdn.net/craftsman2020/article/details/107289222)

1、建表

-------------------------
-- Create Customers table
-------------------------
CREATE TABLE Customers
(
  cust_id      char(10)  NOT NULL ,
  cust_name    char(50)  NOT NULL ,
  cust_address char(50)  NULL ,
  cust_city    char(50)  NULL ,
  cust_state   char(5)   NULL ,
  cust_zip     char(10)  NULL ,
  cust_country char(50)  NULL ,
  cust_contact char(50)  NULL ,
  cust_email   char(255) NULL 
);

--------------------------
-- Create OrderItems table
--------------------------
CREATE TABLE OrderItems
(
  order_num  int          NOT NULL ,
  order_item int          NOT NULL ,
  prod_id    char(10)     NOT NULL ,
  quantity   int          NOT NULL ,
  item_price decimal(8,2) NOT NULL 
);

----------------------
-- Create Orders table
----------------------
CREATE TABLE Orders
(
  order_num  int      NOT NULL ,
  order_date datetime NOT NULL ,
  cust_id    char(10) NOT NULL 
);

------------------------
-- Create Products table
------------------------
CREATE TABLE Products
(
  prod_id    char(10)      NOT NULL ,
  vend_id    char(10)      NOT NULL ,
  prod_name  char(255)     NOT NULL ,
  prod_price decimal(8,2)  NOT NULL ,
  prod_desc  varchar(1000) NULL 
);

-----------------------
-- Create Vendors table
-----------------------
CREATE TABLE Vendors
(
  vend_id      char(10) NOT NULL ,
  vend_name    char(50) NOT NULL ,
  vend_address char(50) NULL ,
  vend_city    char(50) NULL ,
  vend_state   char(5)  NULL ,
  vend_zip     char(10) NULL ,
  vend_country char(50) NULL 
);

----------------------
-- Define primary keys
----------------------
ALTER TABLE Customers WITH NOCHECK ADD CONSTRAINT PK_Customers PRIMARY KEY CLUSTERED (cust_id);
ALTER TABLE OrderItems WITH NOCHECK ADD CONSTRAINT PK_OrderItems PRIMARY KEY CLUSTERED (order_num, order_item);
ALTER TABLE Orders WITH NOCHECK ADD CONSTRAINT PK_Orders PRIMARY KEY CLUSTERED (order_num);
ALTER TABLE Products WITH NOCHECK ADD CONSTRAINT PK_Products PRIMARY KEY CLUSTERED (prod_id);
ALTER TABLE Vendors WITH NOCHECK ADD CONSTRAINT PK_Vendors PRIMARY KEY CLUSTERED (vend_id);

----------------------
-- Define foreign keys
----------------------
ALTER TABLE OrderItems ADD
CONSTRAINT FK_OrderItems_Orders FOREIGN KEY (order_num) REFERENCES Orders (order_num),
CONSTRAINT FK_OrderItems_Products FOREIGN KEY (prod_id) REFERENCES Products (prod_id);
ALTER TABLE Orders ADD 
CONSTRAINT FK_Orders_Customers FOREIGN KEY (cust_id) REFERENCES Customers (cust_id);
ALTER TABLE Products ADD
CONSTRAINT FK_Products_Vendors FOREIGN KEY (vend_id) REFERENCES Vendors (vend_id);

2、插入数据

-- Populate Customers table
---------------------------
INSERT INTO Customers(cust_id, cust_name, cust_address, cust_city, cust_state, cust_zip, cust_country, cust_contact, cust_email)
VALUES('1000000001', 'Village Toys', '200 Maple Lane', 'Detroit', 'MI', '44444', 'USA', 'John Smith', '[email protected]');
INSERT INTO Customers(cust_id, cust_name, cust_address, cust_city, cust_state, cust_zip, cust_country, cust_contact)
VALUES('1000000002', 'Kids Place', '333 South Lake Drive', 'Columbus', 'OH', '43333', 'USA', 'Michelle Green');
INSERT INTO Customers(cust_id, cust_name, cust_address, cust_city, cust_state, cust_zip, cust_country, cust_contact, cust_email)
VALUES('1000000003', 'Fun4All', '1 Sunny Place', 'Muncie', 'IN', '42222', 'USA', 'Jim Jones', '[email protected]');
INSERT INTO Customers(cust_id, cust_name, cust_address, cust_city, cust_state, cust_zip, cust_country, cust_contact, cust_email)
VALUES('1000000004', 'Fun4All', '829 Riverside Drive', 'Phoenix', 'AZ', '88888', 'USA', 'Denise L. Stephens', '[email protected]');
INSERT INTO Customers(cust_id, cust_name, cust_address, cust_city, cust_state, cust_zip, cust_country, cust_contact)
VALUES('1000000005', 'The Toy Store', '4545 53rd Street', 'Chicago', 'IL', '54545', 'USA', 'Kim Howard');

-------------------------
-- Populate Vendors table
-------------------------
INSERT INTO Vendors(vend_id, vend_name, vend_address, vend_city, vend_state, vend_zip, vend_country)
VALUES('BRS01','Bears R Us','123 Main Street','Bear Town','MI','44444', 'USA');
INSERT INTO Vendors(vend_id, vend_name, vend_address, vend_city, vend_state, vend_zip, vend_country)
VALUES('BRE02','Bear Emporium','500 Park Street','Anytown','OH','44333', 'USA');
INSERT INTO Vendors(vend_id, vend_name, vend_address, vend_city, vend_state, vend_zip, vend_country)
VALUES('DLL01','Doll House Inc.','555 High Street','Dollsville','CA','99999', 'USA');
INSERT INTO Vendors(vend_id, vend_name, vend_address, vend_city, vend_state, vend_zip, vend_country)
VALUES('FRB01','Furball Inc.','1000 5th Avenue','New York','NY','11111', 'USA');
INSERT INTO Vendors(vend_id, vend_name, vend_address, vend_city, vend_state, vend_zip, vend_country)
VALUES('FNG01','Fun and Games','42 Galaxy Road','London', NULL,'N16 6PS', 'England');
INSERT INTO Vendors(vend_id, vend_name, vend_address, vend_city, vend_state, vend_zip, vend_country)
VALUES('JTS01','Jouets et ours','1 Rue Amusement','Paris', NULL,'45678', 'France');

--------------------------
-- Populate Products table
--------------------------
INSERT INTO Products(prod_id, vend_id, prod_name, prod_price, prod_desc)
VALUES('BR01', 'BRS01', '8 inch teddy bear', 5.99, '8 inch teddy bear, comes with cap and jacket');
INSERT INTO Products(prod_id, vend_id, prod_name, prod_price, prod_desc)
VALUES('BR02', 'BRS01', '12 inch teddy bear', 8.99, '12 inch teddy bear, comes with cap and jacket');
INSERT INTO Products(prod_id, vend_id, prod_name, prod_price, prod_desc)
VALUES('BR03', 'BRS01', '18 inch teddy bear', 11.99, '18 inch teddy bear, comes with cap and jacket');
INSERT INTO Products(prod_id, vend_id, prod_name, prod_price, prod_desc)
VALUES('BNBG01', 'DLL01', 'Fish bean bag toy', 3.49, 'Fish bean bag toy, complete with bean bag worms with which to feed it');
INSERT INTO Products(prod_id, vend_id, prod_name, prod_price, prod_desc)
VALUES('BNBG02', 'DLL01', 'Bird bean bag toy', 3.49, 'Bird bean bag toy, eggs are not included');
INSERT INTO Products(prod_id, vend_id, prod_name, prod_price, prod_desc)
VALUES('BNBG03', 'DLL01', 'Rabbit bean bag toy', 3.49, 'Rabbit bean bag toy, comes with bean bag carrots');
INSERT INTO Products(prod_id, vend_id, prod_name, prod_price, prod_desc)
VALUES('RGAN01', 'DLL01', 'Raggedy Ann', 4.99, '18 inch Raggedy Ann doll');
INSERT INTO Products(prod_id, vend_id, prod_name, prod_price, prod_desc)
VALUES('RYL01', 'FNG01', 'King doll', 9.49, '12 inch king doll with royal garments and crown');
INSERT INTO Products(prod_id, vend_id, prod_name, prod_price, prod_desc)
VALUES('RYL02', 'FNG01', 'Queen doll', 9.49, '12 inch queen doll with royal garments and crown');

------------------------
-- Populate Orders table
------------------------
INSERT INTO Orders(order_num, order_date, cust_id)
VALUES(20005, '2020-05-01', '1000000001');
INSERT INTO Orders(order_num, order_date, cust_id)
VALUES(20006, '2020-01-12', '1000000003');
INSERT INTO Orders(order_num, order_date, cust_id)
VALUES(20007, '2020-01-30', '1000000004');
INSERT INTO Orders(order_num, order_date, cust_id)
VALUES(20008, '2020-02-03', '1000000005');
INSERT INTO Orders(order_num, order_date, cust_id)
VALUES(20009, '2020-02-08', '1000000001');

----------------------------
-- Populate OrderItems table
----------------------------
INSERT INTO OrderItems(order_num, order_item, prod_id, quantity, item_price)
VALUES(20005, 1, 'BR01', 100, 5.49);
INSERT INTO OrderItems(order_num, order_item, prod_id, quantity, item_price)
VALUES(20005, 2, 'BR03', 100, 10.99);
INSERT INTO OrderItems(order_num, order_item, prod_id, quantity, item_price)
VALUES(20006, 1, 'BR01', 20, 5.99);
INSERT INTO OrderItems(order_num, order_item, prod_id, quantity, item_price)
VALUES(20006, 2, 'BR02', 10, 8.99);
INSERT INTO OrderItems(order_num, order_item, prod_id, quantity, item_price)
VALUES(20006, 3, 'BR03', 10, 11.99);
INSERT INTO OrderItems(order_num, order_item, prod_id, quantity, item_price)
VALUES(20007, 1, 'BR03', 50, 11.49);
INSERT INTO OrderItems(order_num, order_item, prod_id, quantity, item_price)
VALUES(20007, 2, 'BNBG01', 100, 2.99);
INSERT INTO OrderItems(order_num, order_item, prod_id, quantity, item_price)
VALUES(20007, 3, 'BNBG02', 100, 2.99);
INSERT INTO OrderItems(order_num, order_item, prod_id, quantity, item_price)
VALUES(20007, 4, 'BNBG03', 100, 2.99);
INSERT INTO OrderItems(order_num, order_item, prod_id, quantity, item_price)
VALUES(20007, 5, 'RGAN01', 50, 4.49);
INSERT INTO OrderItems(order_num, order_item, prod_id, quantity, item_price)
VALUES(20008, 1, 'RGAN01', 5, 4.99);
INSERT INTO OrderItems(order_num, order_item, prod_id, quantity, item_price)
VALUES(20008, 2, 'BR03', 5, 11.99);
INSERT INTO OrderItems(order_num, order_item, prod_id, quantity, item_price)
VALUES(20008, 3, 'BNBG01', 10, 3.49);
INSERT INTO OrderItems(order_num, order_item, prod_id, quantity, item_price)
VALUES(20008, 4, 'BNBG02', 10, 3.49);
INSERT INTO OrderItems(order_num, order_item, prod_id, quantity, item_price)
VALUES(20008, 5, 'BNBG03', 10, 3.49);
INSERT INTO OrderItems(order_num, order_item, prod_id, quantity, item_price)
VALUES(20009, 1, 'BNBG01', 250, 2.49);
INSERT INTO OrderItems(order_num, order_item, prod_id, quantity, item_price)
VALUES(20009, 2, 'BNBG02', 250, 2.49);
INSERT INTO OrderItems(order_num, order_item, prod_id, quantity, item_price)
VALUES(20009, 3, 'BNBG03', 250, 2.49);

3、数据类型

类型 说明
char(n) 固定长度字符串,表示n个字符的固定长度字符串
varchar(n) 可变长度字符串,表示最多可以有n个字符的字符串
int 整型,也可以用integer
smallint 短整型
numeric(p,d) 定点数p为整数位,n为小数位
real 浮点数
double precision 双精度浮点型
float(n) n为浮点型
boolean 布尔型
date 日期型

4、函数

(1) Aggregate函数

-- 函数,基本类型可分为Aggregate函数 和 Scalar函数
/*
Aggregate函数:
AVG(column)	  返回某列的平均值
COUNT(column) 返回某列的行数(不包括 NULL 值)
COUNT(*)	  返回被选行数
FIRST(column) 返回指定的字段中第一个记录的值.(可使用 ORDER BY 语句对记录进行排序).语法:SELECT FIRST(column_name) FROM table_name
LAST(column)  返回指定的字段中最后一个记录的值.(可使用 ORDER BY 语句对记录进行排序).语法:SELECT LAST(column_name) FROM table_name
MAX(column)	  返回某列的最高值
MIN(column)	  返回某列的最低值
SUM(column)	  返回某列的总和
STDEV(column)	  返回某列的样本标准差
STDEVP(column)	  返回某列的总体标准差
VAR(column)	  返回某列的样本方差
VARP(column)     返回某列的总体方差
区别联系:
1.STDEV求的是样本的标准差,STDEVP求的是总体的标准差,二者的分母不同,前者是n-1,后者是N.
2.VAR是样本的方差,VARP是总体的方差
3.STDEV=SQRT(VAR),STDEVP=SQRT(VARP)
*/

要点:注意count(*)与count(column)的区别

(2) 文本处理函数

/* 文本处理函数
LEFT()  返回字符串左边的字符
RIGHT()  返回字符串右边的字符
LENGTH()或LEN()  返回字符串的长度
UPPER()  将字符串转换为大写
LOWER()  将字符串转换为小写
LTRIM()  去掉字符串左边的空格
RTRIM()  去掉字符串右边的空格
SOUNDEX() 将任何文本串转换为其语音表示的字母数字模式的算法,考虑了类似的发音字符和音节,使得对字符串进行发音比较,而非字母比较.
REPLACE(string_expression, string_pattern, string_replacement) 将String中所有出现的 string_pattern替换为string_replacement.如果任何一个参数为 NULL,则返回 NULL。
*/
-- 取字符串左边两个字符
select LEFT('Michael Green', 2) as res

-- 若Customers表中顾客Kids Place的联系人名误写为Michelle Green.实际为Michael Green.则通过SOUNDEX匹配出发音类似于Michael Green的名子.
SELECT cust_name, cust_contact 
FROM Customers
WHERE SOUNDEX(cust_contact) = SOUNDEX('Michael Green');

-- REPLACE
declare @str varchar(100)
set @str='Hello   Work'
select  @str
select REPLACE(@str,' ','-');
select REPLACE(@str,' ',null);

10分钟学会SQL server_第1张图片

(3) 日期和时间处理函数


-- 日期和时间处理函数
/*
GETDATE() 返回当前的日期和时间

获取时间中单独的年,月,日和时,分,秒
YEAR(GetDate())  当前时间的年部分
MONTH(GetDate()) 当前时间的月部分
DAY(GetDate())   当前时间的日部分
依次类推,上面几个函数是返回INT类型的值,下面这个返回NVARCHAR
DATENAME( YEAR , GetDate() )
DATENAME( MONTH , GetDate() )
DATENAME( DAY , GetDate() )

DATEDIFF()  计算两个日期类型的时间间隔
DATEDIFF( YEAR , '2013-01-01' , '2014-01-01')  返回 1
DATEDIFF( MONTH , '2013-01-01' , '2014-01-01')  返回 12
DATEDIFF( DAY , '2013-01-01' , '2014-01-01')  返回 365

-- 时间格式转换
CONVERT ( data_type [ ( length ) ] , expression [ , style ] )

-- 判断当天是星期几
select datepart(dw,getdate()) -1

-- 判断当天是第几季度
(MONTH(GetDate())-1)/4 +1
*/
-- 获取当前时间
select GETDATE() as currentdatetime;

DECLARE @Date  DATETIME 
SET @Date=GETDATE() 
--前一天,给定日期的前一天 
SELECT DATEADD(DAY,-1,@Date) AS '前一天' 
--后一天,给定日期的后一天  
SELECT DATEADD(DAY,1,@Date) AS '后一天' 
GO 

--月初,计算给定日期所在月的第一天 
--这个计算的技巧是先计算当前日期到“1900-01-01”的时间间隔数,然后把它加到“1900-01-01”上来获得特殊的日期,这个技巧可以用---来计算很多不同的日期。 
DECLARE @Date  DATETIME 
SET @Date=GETDATE() 
SELECT DATEADD(MONTH,DATEDIFF(MONTH,'1900-01-01',@Date),'1900-01-01') AS '所在月的第一天' 
--精简算法,根据SQL Server的时间表示方式可知,'1900-01-01' 可以用0代替 
SELECT DATEADD(MONTH,DATEDIFF(MONTH,0,@Date),0) AS '所在月的第一天' 
--上面两种算法精确到天 时分秒均为00:00:00.000 
--下面算法课以保留时分秒 
--思路:用给定日期减去月第一天与给定日期差的天数 
SELECT DATEADD(DAY,1-DATEPART(DAY,@Date),@Date) 
GO 

-- 返回当前日期,格式为 07/14/20
select CONVERT(varchar(100), GETDATE(), 1)  
-- 最常用的参数是23, 112, 分别返回的格式为2020-07-14、20200714

10分钟学会SQL server_第2张图片

(4) 数值处理函数


-- 数值处理函数
/*
ABS()  绝对值
COS()  余弦
SIN()  正弦
TAN()  正切
EXP()  返回一个数的指数值
PI()   返回圆周率
SQRT() 返回一个数的平方根
*/
select sqrt(100)
select EXP(2)

10分钟学会SQL server_第3张图片

(6) 其他函数

-- 其他函数
/*
CAST (expression AS data_type)  其中expression:任何有效的SQServer表达式。 AS:用于分隔两个参数,在AS之前的是要处理的数据,在AS之后是要转换的数据类型。
                                data_type:目标系统所提供的数据类型,包括bigint和sql_variant,不能使用用户定义的数据类型。
*/

/*
参考:
sql server 时间算法总结: https://www.cnblogs.com/psunny/archive/2010/09/03/1817177.html
sql教程:https://www.w3school.com.cn/sql/sql_functions.asp
covert时间转换函数的 时间格式 参数:https://www.jb51.net/article/23852.htm
sql server 日期与时间操作技巧总结:https://www.jb51.net/Special/784.htm
*/

5、增删改查

详细请参考:
sql server 增删改查
https://blog.csdn.net/craftsman2020/article/details/107289222
SELECT子句 的功能及其顺序

子句 说明 是否必须使用
SELECT 要返回的列或者表达式
FROM 从中检索数据的表 仅在从表里选择数据时使用
WHERE 行级查询
GROUP BY 分组说明 仅在按组计算聚集时使用
HAVING 组间过滤(用在GROPUP BY之后)
ORDER BY 设置输出排序顺序
LIMIT 要检索的函数

附录

系统掌握SQL Server增删改查

你可能感兴趣的:(SQL,Server)