1、两列数据:
c1 c2
1 4
2 5
3 6
如何转换两行显示:
1 2 3
4 5 6
解答:常见的行转列是使用case when 或者decode函数,列转换的换差不多,结果如下:
select max(case when c1=1 then 1 else 0 end) as 'col1',max(case when c1=2 then 2 else 0 end) as 'col2',max(case when c1=3 then 3 else 0 end) as 'col3' from tab4
union
select max(case when c2=4 then 4 else 0 end) as 'col1',max(case when c2=5 then 5 else 0 end) as 'col2',max(case when c2=6 then 6 else 0 end) as 'col3' from tab4;
2、一个表由三列(deptno,ename,sal),查找每个部门工资前三高的员工:
通用sql:
select deptno,ename,sal from emp e1
where (select count(1) from emp e2 where e2.deptno=e1.deptno and e2.sal>=e1.sal) <=3
order by deptno,sal desc;
oracle 查询,利用开窗函数:
select * from (
select deptno,ename,sal,row_number() over (partition by deptno order by sal desc) rn from emp)
where rn<=3;
3、表形式如下:
Year Salary
2000 1000
2001 2000
2002 3000
2003 4000
想得到如下形式的查询结果
Year Salary
2000 1000
2001 3000
2002 6000
2003 10000
sql语句怎么写?
连接查询
SELECT b.YEAR, SUM(a.salary) salary FROM hello a, hello b WHERE a.YEAR <= b.YEAR GROUP BY b.YEAR ;
4、
用一条SQL语句查询出每门课都大于80分的学生姓名
name kecheng fenshu
张三 语文 81
张三 数学 75
李四 语文 76
李四 数学 90
王五 语文 81
王五 数学 100
王五 英语 90
select distinct name from table where name not in (select distinct name from table where fenshu<=80)
另外一个答案是:
select name from table group by name having min(fenshu)>80;
5、如何删除重复数据?
如果是重复数据都删掉的话,如下:
delete from table where id in (select id from table group by id having count(id)>1);
如果重复数据保留一条的话,如下:
delete from table where id in (select id from table group by id having count(id)>1)
and rowid not in (select min(id) from table group by id having count(id)>1);
6、有三个字段id int,birth_date date,salary decimal(18,2),查询出年龄超过50岁,工资最低的5位的平均工资;
select avg(salary) from (select salary from dept where 2018-date_format(birth_date,'%YY')+0>50 group by salary desclimit 5);
7、有一个上亿条记录的大表,现只保留一个字段A1,只包含数字和字母,如何查找?
因为前提条件是上亿条记录,所以需要做些优化,比如分区和索引,这样可以加快查询速度,然后实现的SQL是使用了正则表达式:只保留一个字段,可以尝试做一个视图,然后在视图上做正则表达式。
select col from tab6 where col regexp '^[a-z|A-Z|0-9]*$';