首页 > 代码库 > T-SQL查询1

T-SQL查询1

一些常用的查询和高级查询

? 基本常用查询

 

--select
select * from student;
 
--all 查询所有
select all sex from student;
 
--distinct 过滤重复
select distinct sex from student;
 
--count 统计
select count(*) from student;
select count(sex) from student;
select count(distinct sex) from student;
 
--top 取前N条记录
select top 3 * from student;
 
--alias column name 列重命名
select id as 编号, name ‘名称‘, sex 性别 from student;
 
--alias table name 表重命名
select id, name, s.id, s.name from student s;

 

--column 列运算
select (age + id) col from student;
select s.name + ‘-‘ + c.name from classes c, student s where s.cid = c.id;

--where 条件
select * from student where id = 2;

--and 并且
select * from student where id > 2 and sex = 1;
 
--or 或者
select * from student where id = 2 or sex = 1;

--between ... and ... 之间
select * from student where id between 2 and 5;
select * from student where id not between 2 and 5;

--like 模糊查询
select * from student where name like  ‘%a%‘;

 

--in 子查询
select * from student where id in (1, 2);
 
--not in 不在其中
select * from student where id not in (1, 2);
 
--is null 是空
select * from student where age is null;
 
--is not null 不为空
select * from student where age is not null;
 
--order by 排序
select * from student order by name;
select * from student order by name desc;
select * from student order by name asc;
 
--group by 分组
按照年龄进行分组统计
select count(age), age from student group by age;
按照性别进行分组统计
select count(*), sex from student group by sex;
按照年龄和性别组合分组统计,并排序
select count(*), sex from student group by sex, age order by age;
按照性别分组,并且是id大于2的记录最后按照性别排序
select count(*), sex from student where id > 2 group by sex order by sex;
查询id大于2的数据,并完成运算后的结果进行分组和排序
select count(*), (sex * id) new from student where id > 2 group by sex * id order by sex * id;

--group by all 所有分组
按照年龄分组,是所有的年龄
select count(*), age from student group by all age;

group by all与group by的区别

当你使用WHERE语句过滤数据时,结果分组中只显示你指定的那些记录,而符合分组定义但是不满足过滤条件的数据不会包含在某个分组中。当你想在分组中包含所有数据时添加关键字ALL即可,这时WHERE条件就不起作用。例如,在前面的例子中添加关键字ALL就会返回所有的ZIP分组,而不是仅在肯塔基州的那些。  

<ccid_nobr>
<ccid_code>SELECT ZIP FROM CustomersWHEREState = ‘‘KY‘‘ GROUP BY ALL ZIP

     这样看来,这两个语句存在冲突,你可能不会以这种方式使用关键字ALL。当你使用聚合函数计算某一列时,使用ALL关键字可能会很方便。例如,下面的语句计算每个肯塔基州ZIP中的顾客数,同时,还会显示其它的ZIP值。 

<ccid_nobr>
<ccid_code>SELECT ZIP, Count(ZIP) AS KYCustomersByZIP FROM
            CustomersWHEREState = ‘‘KY‘‘ GROUP BY ALL ZIP

结果分组包括潜在数据中的所有ZIP值,然而,对于那些不是肯塔基州ZIP分组的聚合列(KYCustomersByZIP)将会显示0。远程查询不支持GROUP BY ALL。

 

--having 分组过滤条件
按照年龄分组,过滤年龄为空的数据,并且统计分组的条数和现实年龄信息
select count(*), age from student group by age having age is not null;
 
按照年龄和cid组合分组,过滤条件是cid大于1的记录
select count(*), cid, sex from student group by cid, sex having cid > 1;
 
按照年龄分组,过滤条件是分组后的记录条数大于等于2
select count(*), age from student group by age having count(age) >= 2;
 
按照cid和性别组合分组,过滤条件是cid大于1,cid的最大值大于2
select count(*), cid, sex from student group by cid, sex having cid > 1 and max(cid) > 2;


 

T-SQL查询1