(1)row_number和distinct
distinct和row_number都是用来
去重的,但是又有点分别
1.1 首先看distinct
语法如下:
select distinct 列名称 from 表名称
关键字 distinct 只能放在 SQL 语句中所有字段的最前面才能起作用,如果放错位置,SQL 不会报错,但也不会起到任何效果。
distinct关键字只作用于一个字段,即一个列名,当 distinct 作用在多个字段的时候,她只会将所有字段值都相同的记录“去重”掉
例子如下所示:
*
|
name |
age
|
1
|
赵风
|
18
|
2
|
钱雨
|
20
|
3
|
孙雷
|
21
|
4
|
李电
|
18
|
5
|
李电
|
22
|
select distinct name,age from student
得到结果如下:
*
|
name
|
age
|
1
|
李电
|
18
|
2
|
钱雨
|
20
|
3
|
孙雷
|
21
|
4
|
赵风
|
18
|
5
|
李电
|
22
|
1.2 row_number()over()
在 SQL Server 数据库中,为咱们提供了一个函数 row_number() 用于给数据库表中的记录进行标号,在使用的时候,其后还跟着一个函数 over(),而函数 over() 的作用是将表中的记录进行分组和排序,使用语法如下所示:
select row_number() over(partition by cid order by score desc) as sort,* from sc
--pratition by cid 这个就是用 字段cid 来排序对比的
--order by score 根据score进行排序(后面添加desc,所以是根据score进行降序排序的)
(2)left join,right join 和inner join
left join(左联接) 返回包括
左表中的所有记录和右表中联结字段相等的记录
right join(右联接) 返回包括
右表中的所有记录和左表中联结字段相等的记录
inner join(等值连接) 只返回
两个表中联结字段相等的行
(3) case when then else end
相当于C#里面的if--else
具体实例如下:
具体代码如下;
--23☆☆☆、统计各科成绩各分数段人数:课程编号,课程名称,[100-85],[85-70],[70-60],[0-60]及所占百分比 --思路:SC表和COURSE表联合查询(一个记录集合),然后每个字段都看做是一个子查询,最后将这些子查询拼接起来。 select a.Cid as '课程编号',b.Cname as '课程名称' ,count(1)as '总人数' , count(case when a.score<60 then 1 else null end) as '不及格人数',convert(decimal(5,2), count(case when a.score>=0 and a.score<60 then 1 else null end)*100/count(1)) as '不及格率%', count(case when a.score>=60 and a.score<70 then 1 else null end) as '及格人数',convert(decimal(5,2), count(case when a.score>=60 and a.score<70 then 1 else null end)*100/count(1)) as '及格率%', count(case when a.score>=70 and a.score<85 then 1 else null end) as '优良人数',convert(decimal(5,2), count(case when a.score>=70 and a.score<85 then 1 else null end)*100/count(1)) as '优良率%', count(case when a.score>=85 then 1 else null end) as '优秀人数',convert(decimal(5,2), count(case when a.score>=85 then 1 else null end)*100/count(1)) as '优秀率%' from sc a left join Course b on a.Cid=b.Cid group by a.Cid,b.Cname
(4)保留两位小数代码如下所示:
CAST( count(case when a.score>0and a.score<60 then 1 else null end)*1.00/count(1)as decimal(18,2)) as '不及格率'
其中cast函数是转换数据类型的函数,cast((需要转换的数据)as 数据类型);
前面一定要乘于1.00,否则算出来的不及格率为0(让我想起了C#里面要保留两位小数就直接乘于1.00);
除号前后分别用cast转换得不到保留两位数,我也不知道什么原因 !!