必须会的SQL语句(六) 数据查询
1.基础的查询
1)重命名列
select name as '姓名' from 表名
2)定义常量列
select 是否 ='是' from 表名
3)top用法 percent
--这种写法可以获取前20%条字段。
select top 20 percent * from 表名
4)去除重复列
select distinct 列名 from 表名
5)聚合函数
max avg count min sum
--多个聚合结果 在一个结果集中
select
最大年龄 = (select max(age) from 表名),
最小年龄 = (select min(age) from 表名)
6)between and
select * from 表 where xx between 5 and 6
2.Union 使用Union将两个结果集汇聚在一起。
-- 年龄 工资
-- ――――――――
-- 19 $20000
-- 50 $20005
-- 30 $23000
-- 汇总 $63005
-- 查询各年龄段工资,同时显示所有工资汇总。(像上边的表)
select
--把年龄转换成varchar类型
Convert(varchar(10),[age]) as 年龄
Sum([salary]) as 工资
from 员工表
group by age
--将两个结果集,合并成一个结果集
union
select
--汇总是一个常量列
'汇总' , sum(salary)
from 员工表
使用union合并两个结果集时,
两个结果集列数必须一致,并且数据类型对应。
这就是代码中,把年龄转换成varchar的原因。
3.Order by
-- Order by 用于结果集排序,
-- 其Order他后边不只可以接一个字段,
-- 也能接一个 表达式。
Select *
from 表
order by (age+salary)/2.0 desc
您可能感兴趣的文章:
- 必须会的SQL语句(六) 数据查询
- 全面复习之 SQL(2)-数据查询语句
- 学习数据库必须掌握的54条SQL查询语句
- thinkphp中多表查询中防止数据重复的sql语句(必看)
- 数据库SQL语句查询指定时间段内的数据
- 查询和删除表中重复数据sql语句
- SQL 语句查询指定某日期的数据
- sql语句无错误 order by 和limit一起用数据查询不准有重复
- 使用SQL语句中between and查询数据出错
- 从Mysql某一表中随机读取n条数据的SQL查询语句
- 根据会员编号、会员名称、会员积分、店铺编号查询数据的简单方法(sql语句)
- ADO带密码的数据连接、查询一个记录集、执行一SQL语句
- SQL SERVER2000教程-第五章 处理数据 第二十二节 利用UNION对多条SQL查询语句合并生成表
- SQL查询重复数据,只显示一条sql语句
- 基于SQL中的数据查询语句汇总
- mybatis执行查询语句查询不到结果,控制台输出sql语句复制到数据库中能查到数据
- 动态sql语句基本语法(字段名,表名,数据库名之类作为变量时,必须用动态SQL如ALTER TABLE中使用程序传递的参数)
- 学习数据库必须掌握的54条SQL查询语句
- SQL语句查询指定的数据,查询只选择了指定4门课程的学生
- 程序员老鸟写sql语句的经验之谈、百万数据查询优化技巧三十则