select *from car
--like 模糊
select top 3 *from car where name like ‘宝马%‘ --like ‘%%‘ 模糊查询 %%代表什么可以有字符,后面也可以有任何字符
select top 3 *from car where name like ‘宝马_‘ --代表宝马可以有一个字符
select top 3 *from car where name like ‘宝马[1-9]_‘ --代表‘宝马’后面第一个字符为1-9的数字
select top 3 *from car where name like ‘宝马[^1-9]_‘ --代表‘宝马’后面第一个字符不是1-9的数字
--distinct 去重复
select distinct brand from car --去除brand这一列重复的
--asc desc 排序
select *from car order by oil asc --按照oil的从低到高排序
select *from car order by oil desc --从高到低
select top 1 *from car order by oil asc --oil最低的一个
select top 1 *from car where name like ‘%宝马%‘ order by oil asc --宝马中oil最低的一个
--比较运算符 < > <= >= !=
--逻辑运算符 and or
select *from car where name like ‘%宝马%‘ and price < 50 --宝马50万一下的 and 并且的意思
--聚合函数: max,min,sum,count,avg
select MIN(oil) as 最低油耗 from car --最低油耗
select *from car where oil in (select MIN(oil) from car) --最低油耗
select MAX(oil) from car --最大
select AVG(oil) from car --平均值
select COUNT ( *)from car --个数
--group by 分组
select brand, MIN(price) as 价格最高 from car group by brand --group by 按照**分组
select brand,COUNT(*) from car group by brand having COUNT(*)>=1--having 再次筛选
--日期时间函数
select SYSDATETIME() --获取系统时间
select GETDATE() --获取系统时间
select YEAR(GETDATE()) --获取当前系统的年份
select YEAR(‘2015-9-2‘)
select DATENAME (YEAR,‘2015-1-1‘)
select DATENAME(DAYOFYEAR,GETDATE()) --第多少天 返回的是字符串
select DATEpart(DAYOFYEAR,GETDATE()) --第多少天 返回的是int
select DATEPART(YEAR,GETDATE())
select DATENAME(WEEKDAY,GETDATE()) --第几天 返回的是星期几
select DATEpart(WEEKDAY,GETDATE()) --返回的是数字
select DATEADD(DAY,50,GETDATE()) --在系统时间上面增加50天
--字符串函数
select STR(123.45,6,1) --四舍五入 6表示一共保留几位,1表示小数点后几位
select REPLACE(‘1234567‘,‘234‘,‘xxx‘) --搜索1234567,把234替换成xxx
select LEFT(‘1234567‘,2) --从左边开始截取2个字符,输出为12
select RIGHT(‘1234567‘,2) --从右边开始截取2个字符,输出结果为67
select LEN(‘fsadf‘) --返回字符串的长度
select REVERSE(‘12345‘) --反转字符串
select upper(‘fsdf‘) --转换成大写
select LOWER(‘DFA‘) --转换成小写
select LTRIM(‘ sdfadf ‘)--去除前空格
select rTRIM(‘ sdfadf ‘)--去除后空格
select SUBSTRING(‘adfadf‘,4,2)--从4开始截取2个字符串
select *from car where CEILING(oil)>8 --取上限
--类型转换
select CAST(‘123‘ as int) --as转换类型
select CONVERT(int, ‘123‘)--也是类型转换
select ‘123‘+‘234‘ --输出结果为123234
--把car中time这一列中换成年月日的形式
select ids,code,name,brand,
CAST(YEAR(time) as varchar(10))+‘年‘
+CAST(MONTH(time) as varchar(10))+‘月‘
+CAST(DAY(time) as varchar(10))+‘日‘ as time,
oil,powers,exhaust,price,pic from car
select *from car
select *from brand
--子查询
select ids,code,name,(select brand_name from brand where brand_code=car.brand)as brand_name from car
select ids,code,name,brand_name from car inner join brand on car.brand=brand.brand_code
select ids,code,name,brand_name from car left join brand on car.brand=brand.brand_code
select ids,code,name,brand_name from car right join brand on car.brand=brand.brand_code