SQL Server 具体查询要点,自己整理

1,distinct 对某一列进行去重

检索有职工的工资大于或等于wh1仓库中任何一名职工工资的仓库号

select distinct cno from zhigongbiao where gongzi >= (select Min(gongzi) from zhigongbiao where cno in ('wh1'))

2 ,between   and   在...之间

检索出工资在1220元到1240元范围内的职工信息。

select *from zhigongbiao where gongzi between 1220 and 1240

3,order by    desc ,asc  将一列进行升序或降序排列

先按仓库号排序,再按工资排序并输出全部职工信息

select*from zhigongbiao order by cno asc,gongzi desc

4,join  on     表连接,表示横向表连接

找出工作在面积大于400的仓库的职工号以及这些职工工作所在的城市

select zno ,city from cangkubiao join zhigongbiao on cangkubiao.cno=zhigongbiao .cno where mianji>400

5, union  表连接,表示纵向表链接

union 中的所有选择列表必须具有相同的列数,相似的数据类型和相同的顺序

结果集中的列名来自第一个select 语句

6, 相关子查询, 

列出每个职工经手的具有最高总金额的订购单信息   --重点题目,相关子查询 

select*from dingdanbiao a where dingdanzongjia  not in (select MAX(dingdanzongjia) from dingdanbiao b where a.zno=b.zno) 

7, 聚合函数

count ,avg ,sum, max,min 

8,group by  对制定列进行分组   having 在分组的基础上进行进一步筛选,一般与 group by 子句配合使用 

求至少有两个职工的每个仓库的平均工资

select cno,AVG (gongzi) 平均工资 from zhigongbiao group by cno having COUNT(*)>=1

9,子查询(嵌套查询)

使用查询语句查询一列数据出来,然后作为其他查询条件中参数来使用

检索有职工的工资大于或等于wh1仓库中所有职工工资的仓库号。

select cno from zhigongbiao where gongzi >=(select Max(gongzi) from zhigongbiao where cno in ('wh1'))

10, 时间和日期函数

datediff  功能是获取两个日期之间的值

查询Student表中每个学生的姓名和年龄。

select sname,DATEDIFF(YEAR,sbirthdy,getdate()) age from student

day(date),取指定日期的日    month(date),取制定日期的月  year(date) 取制定日期的年

查询和学号为3的同学同年出生的所有学生的Sno、Sname和Sbirthday列。 --重点题目

select sno,sname,sbirthdy from student where YEAR(sbirthdy)=(select YEAR(sbirthdy)from student where sno='3')

11,in ,like,=,>,< 等,还有 top 子句,查询前几行

  查询Score表中的最高分的学生学号和课程号。(子查询或者排序)

select sno,cno from score where degree=(select MAX(degree) from score)

select top 1* sno,cno from score order by degree desc       

 

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