SQL每日一题(2020-05-18)

2020-06-02  本文已影响0人  扎西的德勒

题目:

怎么把下面的表(tab)

image

查成这样1个结果

image

考点:行列转换

参考答案:

数据库版本:Server version: 8.0.20 MySQL Community Server - GPL

建表语句

create table dailytest_20200518
(
    year   int,
    month  int,
    amount double
);

数据准备

insert into dailytest_20200518 values(2017,1,1.1);
insert into dailytest_20200518 values(2017,2,1.2);
insert into dailytest_20200518 values(2017,3,1.3);
insert into dailytest_20200518 values(2017,4,1.4);
insert into dailytest_20200518 values(2018,1,2.1);
insert into dailytest_20200518 values(2018,2,2.2);
insert into dailytest_20200518 values(2018,3,2.3);
insert into dailytest_20200518 values(2018,4,2.4);

查询逻辑

select
       year,
       max(case when month = 1 then amount end) as m1,
       max(case when month = 2 then amount end) as m2,
       max(case when month = 3 then amount end) as m3,
       max(case when month = 4 then amount end) as m4
from dailytest_20200518
group by year

附:
题目来源:https://mp.weixin.qq.com/s/7s2bjL1u7L-vMNUjB-J1fg

上一篇 下一篇

猜你喜欢

热点阅读