lshboo 发表于 2018-10-23 09:01:33

8. SQL -- 查询,集函数,分组

  为了大家更容易理解我举出的SQL语句,本文假定已经建立了一个学生成绩管理数据库,全文均以学生成绩的管理为例来描述。
  1.在查询结果中显示列名:
  a.用as关键字:select name as '姓名' from students order by age
  b.直接表示:select name '姓名' from students order by age
  2.精确查找:
  a.用in限定范围:select * from students where native in ('湖南', '四川')
  b.betweenand:select * from students where age between 20 and 30
  c.“=”:select * from students where name = '李山'
  d.like:select * from students where name like '李%' (注意查询条件中有“%”,则说明是部分匹配,而且还有先后信息在里面,即查找以“李”开头的匹配项。所以若查询有“李”的所有对象,应该命令:'%李%';若是第二个字为李,则应为'_李%'或'_李'或'_李_'。)
  e.[]匹配检查符:select * from courses where cno like '%' (表示或的关系,与"in()"类似,而且"[]"可以表示范围,如:select * from courses where cno like '%')
  3.对于时间类型变量的处理
  a.smalldatetime:直接按照字符串处理的方式进行处理,例如:
  select * from students where birth > = '1980-1-1' and birth 85
  order by 3
  10.其他
  a.对于有空格的识别名称,应该用"[]"括住。
  b.对于某列中没有数据的特定查询可以用null判断,如select sno,courseno from grades where mark IS NULL
  c.注意区分在嵌套查询中使用的any与all的区别,any相当于逻辑运算“||”而all则相当于逻辑运算“&&”
  d.注意在做否定意义的查询是小心进入陷阱:
  如,没有选修‘B2’课程的学生 :
  select students.*
  from students, grades
  where students.sno=grades.sno
  AND grades.cno’B2’
  上面的查询方式是错误的,正确方式见下方:
  select * from students
  where not exists (select * from grades
  where grades.sno=students.sno AND cno='B2')
  11.关于有难度多重嵌套查询的解决思想:
  如,选修了全部课程的学生:
  select *
  from students
  where not exists ( select *
  from courses
  where NOT EXISTS
  (select *
  from grades
  where sno=students.sno
  AND cno=courses.cno))
  最外一重:从学生表中选,排除那些有课没选的。用not exist。由于讨论对象是课程,所以第二重查询从course表中找,排除那些选了课的即可。

  添加数据库

  use master
  go
  if exists (select * from sysdatabases where name='test')
  drop database mlnt
  go
  create database test
  on
  (
  name='test_data',
  filename='D:"SQLSERVER2000"MSSQL"Data"test_data.mdf',
  size=10mb,
  filegrowth=10%
  )
  log on
  (
  name='test_log',
  filename='D:"SQLSERVER2000"MSSQL"Data"test_log.ldf',
  size=10mb,
  filegrowth=10%
  )

  sql server 2005 怎么把性别bit 类型的1、0转换成中文男或女显示啊?
  select case 性别
  when 1 then '男'
  when 0 then '女'
  end as 性别
  from tablea

页: [1]
查看完整版本: 8. SQL -- 查询,集函数,分组