0.问题列表
记录一些做题及面试笔试过程中碰到的MySQL的难题错题
不做题,学的再多也没用
- 题目1~题目5:
- MySQL行转列
- MySQL列转行
1.题目1~题目5:
题目(1)
- 题目:
写一个SQL将数据表B
转换为如下格式: - 答案一:使用函数
也可以使用其他的函数如MIN,SUM等,不过网上多用MAX。SELECT year, MAX( CASE month WHEN 1 THEN b.CODE END ) as m1, MAX( CASE month WHEN 2 THEN b.CODE END ) as m2, MAX( CASE month WHEN 3 THEN b.CODE END ) as m3, MAX( CASE month WHEN 4 THEN b.CODE END ) as m4 from B GROUP BY year;
- 答案二:使用嵌套子查询
但是需要给year字段设置别名,否则会报错,这一点不符合。SELECT DISTINCT year as b_year, (SELECT code FROM B where `year`=b_year and `month`='1') as m1, (SELECT code FROM B where `year`=b_year and `month`='2') as m2, (SELECT code FROM B where `year`=b_year and `month`='3') as m3, (SELECT code FROM B where `year`=b_year and `month`='4') as m4 from b;
结果如下: - 答案三:使用存储过程,动态行转列
如新增month可以不用修改SQL语句
2)题目(2):
最后更新: 2018年05月31日 09:32
原始链接: https://zjxkenshine.github.io/2018/05/31/MySQL笔试面试题总结(一)/