SQL Server常用知识点和日常案例
1. select getdate() // 获取当前日期时间
2020-11-05 22:49:41.227
2. select DATEADD(DD,1,getdate()) --当前日期时间加一天,负数就减 DD 日, MM 月....
2020-11-06 22:54:41.000
3. select concat(name,salary) from test_1 --concat函数可以拼接两个字段
4. left(username , len(username)-1) --去除字段最后一个或多个字符
5. select * into table1 from ( select id, username from users)
--将查询结果复制到另一个表,table1会自动生成
select * into #table1 from (select id ,username from users )
--将查询结果复制到一个临时表
6. insert into table1 select * from users
--将users表复制到table1中,table1必须已存在
7. case when //最多能连续用10个
select id, case username when 'admin' then '管理员' else '用户' end as s from users
select id, case when username='admin' then '管理员' else '用户' end as s from users
8. ISNULL(username,'默认值') --username为空取默认值
9.常用where多条件拼接
where ('' = ISNULL(@username,'') or username = @username) and
('' = ISNULL(@mun,'') or mun = @mun )
10. stuff((select ',' + ep_name from ep_detail where ep_classes = a.ep_classes for xml path('')), 1, 1, '')
-- 一些循环拼接符一般最后面都会多出一个拼接符号,如果使用left( username,len(username)-1),如果username 是表达式的话就会影响性能,
--可以考虑将拼接符拼接到字段前面,再使用stuff函数去除第一个字符,stuff()函数可以达到添加,替换或删除某指定字符的作用。
11. declare @res varchar(10) , @res2 varchar(10)
select @res = beizhu from pingfen where id=1
select @res1='test',@res2='test2'
--变量赋值的第二种方式,可以声明或赋值多个
12.select * from user where not id = 1 ---相当于id <> 1 , 优先级 not > and > or
- with Testtable(username,age) as
(
select username , id from user
)
select * from user where username ='test'
--公共表表达式 ,相当于临时的结果集
- [user] [select]
--一般字段、表名、存储过程名等与关键字或者中文字段较长,都加上中括号
- select 22 / 3 --7
select 22 * 1.0 / 3 --7.33333
--整数相除不会显示小数位,需要分子 乘以1.0
-
- 行转列方法1 ,使用外连接,也可以使用每列添加子查询方式。 (每行不重复,按条件分成指定列)
-- time1 6-8 time2 8-10 time3 10-13
select t.id,username,time1.kqtime time1,time2.kqtime time2,time3.kqtime time3
from tests t
left outer join ( select id,kqtime from tests where kqtime>'06:00' and kqtime< '08:00') time1
on time1.id = t.id
left outer join ( select id,kqtime from tests where kqtime>'08:00' and kqtime< '10:00') time2
on time2.id = t.id
left outer join ( select id,kqtime from tests where kqtime>'10:00' and kqtime< '13:00') time3
on time3.id = t.id
结果如图:
- 按日期获取从当天起一个月之前的数据
//获取当天一个月之前的考勤数据
kqdate between dateadd(d,-30,getdate()) and getdate()