题目链接:点击打开链接
题目大意:略。
解题思路(1)
第一步 列拆成行
首先,根据题意,需要将revenue列根据month拆成行,结果如下表,有两种方式,CASE WHEN或者IF语句。
SELECTid, CASE`month`WHEN'Jan'THENrevenueENDJan_Revenue, CASE`month`WHEN'Feb'THENrevenueENDFeb_Revenue, CASE`month`WHEN'Mar'THENrevenueENDMar_Revenue, CASE`month`WHEN'Apr'THENrevenueENDApr_Revenue, CASE`month`WHEN'May'THENrevenueENDMay_Revenue, CASE`month`WHEN'Jun'THENrevenueENDJun_Revenue, CASE`month`WHEN'Jul'THENrevenueENDJul_Revenue, CASE`month`WHEN'Aug'THENrevenueENDAug_Revenue, CASE`month`WHEN'Sep'THENrevenueENDSep_Revenue, CASE`month`WHEN'Oct'THENrevenueENDOct_Revenue, CASE`month`WHEN'Nov'THENrevenueENDNov_Revenue, CASE`month`WHEN'Dec'THENrevenueENDDec_RevenueFROMDepartment; 或SELECTid, IF(`month`='Jan',revenue,NULL) Jan_Revenue, IF(`month`='Feb',revenue,NULL) Feb_Revenue, IF(`month`='Mar',revenue,NULL) Mar_Revenue, IF(`month`='Apr',revenue,NULL) Apr_Revenue, IF(`month`='May',revenue,NULL) May_Revenue, IF(`month`='Jun',revenue,NULL) Jun_Revenue, IF(`month`='Jul',revenue,NULL) Jul_Revenue, IF(`month`='Aug',revenue,NULL) Aug_Revenue, IF(`month`='Sep',revenue,NULL) Sep_Revenue, IF(`month`='Oct',revenue,NULL) Oct_Revenue, IF(`month`='Nov',revenue,NULL) Nov_Revenue, IF(`month`='Dec',revenue,NULL) Dec_RevenueFROMDepartment; +------+-------------+-------------+-------------+-----+-------------+|id|Jan_Revenue|Feb_Revenue|Mar_Revenue| ... |Dec_Revenue|+------+-------------+-------------+-------------+-----+-------------+|1|null|7000|null| ... |null||3|null|10000|null| ... |null||1|8000|null|null| ... |null||2|9000|null|null| ... |null||1|null|null|6000| ... |null|+------+-------------+-------------+-------------+-----+-------------+
第二步 行合并
其次,根据题意,需要根据id,将相同id的行进行合并,结果如下表,采用分组的方式,可以对各月收入列求和(SUM)也可以求最大值(MAX)。
SELECTid, SUM(CASE`month`WHEN'Jan'THENrevenueEND) Jan_Revenue, SUM(CASE`month`WHEN'Feb'THENrevenueEND) Feb_Revenue, SUM(CASE`month`WHEN'Mar'THENrevenueEND) Mar_Revenue, SUM(CASE`month`WHEN'Apr'THENrevenueEND) Apr_Revenue, SUM(CASE`month`WHEN'May'THENrevenueEND) May_Revenue, SUM(CASE`month`WHEN'Jun'THENrevenueEND) Jun_Revenue, SUM(CASE`month`WHEN'Jul'THENrevenueEND) Jul_Revenue, SUM(CASE`month`WHEN'Aug'THENrevenueEND) Aug_Revenue, SUM(CASE`month`WHEN'Sep'THENrevenueEND) Sep_Revenue, SUM(CASE`month`WHEN'Oct'THENrevenueEND) Oct_Revenue, SUM(CASE`month`WHEN'Nov'THENrevenueEND) Nov_Revenue, SUM(CASE`month`WHEN'Dec'THENrevenueEND) Dec_RevenueFROMDepartmentGROUPBYid; +------+-------------+-------------+-------------+-----+-------------+|id|Jan_Revenue|Feb_Revenue|Mar_Revenue| ... |Dec_Revenue|+------+-------------+-------------+-------------+-----+-------------+|1|8000|7000|6000| ... |null||2|9000|null|null| ... |null||3|null|10000|null| ... |null|+------+-------------+-------------+-------------+-----+-------------+
解题思路(2)