必须会的SQL语句(六) 数据查询

1.基础的查询 1)重命名列 select name as '姓名' from 表名 2)定义常量列 select 是否 ='是' from 表名 3)top用法 percent --这种写法可以获取前20%条字段。 select top 20 percent * from 表名 4)去除重复

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