SQL学习日志

今天看了杨老师的视频,写篇SQL学习日志吧,以此来巩固自己学习的知识!
首先是主键的概念,主键是数据行的唯一标识。不会重复的列,才能当主键,一个表可以没有主键,但是会非常难以处理。 主键有两种选择策略:业务主键和逻辑主键(使用没有任何业务意义),推荐时用逻辑主键。
下面是SQL基础:
1、SQ语句就像和数据库管理器在交谈
2、SQL语句中的字符串用单引号。
3、SQL语句的大小不敏感,关键字不敏感,但是数值敏感 主键的选择:常用int+标识自动增长和uniqueidentifier又称(Guid,具体的SQL语句中用newid()内置函数来获取)目前业务主流推荐使用后者。
常用SQL语句集锦
1、建立一个数据库 create database database-name
2、建立一个表 create table table_name(id int,Name nvarchar(50))
3、删除一个表 drop table tablename
      添加主键 alter table tabname add primary key(col)
      删除主键: alter table tabname drop primary key(col)
4、基本的sql语句总结
选择:select *from table where 范围
插入:insert into table1(id,Name)values(newid(),'Frank')
删除:delete from table1 where 范围
更新:update table1 set field1=value where
查找:select *from table1 where field1 like '%value%'    用like语句查询包含某个东西
排序:select * from table1 order by feild1,feild2 desc(降序)   或者asc(升序)
总数:select count as totalcount from table1     计算总数
求和:select sum(field1)  as sumvalue from table1
平均:select avg(field1)  as sumvalue from table1
最小值:select min(field1)  as sumvalue from table1
最大值:select max(field1)  as sumvalue from table1
5、下面是数据分组:
比如统计各个年龄段的人数
select  Age.Count(*) from table group by Age;
group by必须放在where 后
6、Having语句
where不能使用聚合函数,如果要使用就要用Having,Having在group by之后
7、限制结果的条数:
例如:select top 10 from table order by age desc
如果检索按工资排序从第六名开始的三个人的信息:
select top 3 * from table where num not in (select top 5 * from tabble order by  zongzi  desc) order by gongzi desc
8、抑制重复的数据:
select distinct field1 from table;
select distinct feild1,field2 fron table;feild1和feild2完全重复才被抑制
9、union运算符
Union运算符通过组合其他两个结果表(table1和table2)并消去其中重复行而派生出的一个结果表,当用union all时不会消去重复行,两种情况下派生表不是来自table1就是table2
例如:
select * max(age) from table1
union all
select * min(age) from table 2
10、数据函数
数字函数
abs(),请绝对值
celing() 舍入到最大整数
floor()舍入到最小整数
round()  四舍五入
字符串函数
len()。计算字符串长度
lower()、upper():转小写,转大写
ltrim():去掉字符串左边的空格
rtrim():去掉字符串右边的空格
substring(string,start_position,lehgth)截取字符串,string为字符串,start——position为开始截取的位置,length为子字符串长度
如:select substring('345123',2,3)
日期函数
getdate() 取得当前日期时间
dateadd(datepart,number,date),计算增加以后的日期
如:dateadd(day,3,date)为计算date的3天后的日期
        dateadd(month,-8,date)为计算date的8个月前的日期
datediff(datepart,startdate,enddate):计算两个日期的差额,以datepart为计量单位,这和dateadd相同
datepart(datepart,date):返回日期的特定部分
类型转换函数
cast(expression as date_type)
convert(date_type,expression)
select fidnumber.
right(fidnumber,3) as 后三位
cast(right(fidnumber,3) as integer) as 后三位的整数形式
cast(right(fidnumber,3) as interger)=1 as 后三位加1
convert(interger,right(fidnumber,3))/2 后三位除以2

好了,这就是今天的内容,非常感谢杨老师分享自己的教学视频!

----转载请注明出处http://www.cnblogs.com/JerryWang1991/ 谢谢!
原文地址:https://www.cnblogs.com/JerryWang1991/p/3936399.html