0.问题列表

记录一些做题及面试笔试过程中碰到的MySQL的难题错题
不做题,学的再多也没用

  1. 题目1~题目5:
    • MySQL行转列
    • MySQL列转行

1.题目1~题目5:

题目(1)

  1. 题目:
    写一个SQL将数据表B

    转换为如下格式:
  2. 答案一:使用函数
    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;
    
    也可以使用其他的函数如MIN,SUM等,不过网上多用MAX。
  3. 答案二:使用嵌套子查询
    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;
    
    但是需要给year字段设置别名,否则会报错,这一点不符合。
    结果如下:
  4. 答案三:使用存储过程,动态行转列
    如新增month可以不用修改SQL语句

2)题目(2):


× 请我吃糖~
打赏二维码