1、题目
找出所有员工当前(to_date=‘9999-01-01’)具体的薪水salary情况,对于相同的薪水只显示一次,并按照逆序显示
CREATE TABLE salaries
(
emp_no
int(11) NOT NULL,
salary
int(11) NOT NULL,
from_date
date NOT NULL,
to_date
date NOT NULL,
PRIMARY KEY (emp_no
,from_date
));
2、解答
解答一:group by
select salary from salaries where to_date='9999-01-01' group by salary order by salary desc ;
解答二:distinct
select distinct salary from salaries where to_date='9999-01-01' order by salary desc;
3、解析
distinct使用
大表一般用distinct效率不高,大数据量的时候都禁止用distinct,建议用group by解决重复问题。
对于distinct与group by的使用:
1、当对系统的性能高并数据量大时使用group by
2、当对系统的性能不高时使用数据量少时两者皆可
3、尽量使用group by
SQL中distinct的用法
1.作用于单列
select distinct name from A
2.作用于多列
select distinct name, id from A
3.COUNT统计
select count(distinct name) from A; --表中name去重后的数目, SQL Server支持,而Access不支持
select count(distinct name, id) from A;
select count(*) from (select distinct xing, name from B) AS M;
4.distinct必须放在开头
select id, distinct name from A; --会提示错误,因为distinct必须放在开头
5.其他
distinct语句中select显示的字段
只能是distinct指定的字段
,其他字段是不可能出现的
。例如,假如表A有“备注”列,如果想获取distinc name,以及对应的“备注”字段,想直接通过distinct是不可能实现的。
学习链接:
https://www.nowcoder.com/profile/90965491/codeBookDetail?submissionId=82270501
https://www.cnblogs.com/rainman/archive/2013/05/03/3058451.html