Input: Department table:+------+---------+-------+| id | revenue | month |+------+---------+-------+| 1 | 8000 | Jan || 2 | 9000 | Jan || 3 | 10000 | Feb || 1 | 7000 | Feb || 1 | 6000 | Mar |+------+---------+-------+Output: +------+-------------+-------------+-------------+-----+-------------+| id | Jan_Revenue | Feb_Revenue | Mar_Revenue | ... | Dec_Revenue |+------+-------------+-------------+-------------+-----+-------------+| 1 | 8000 | 7000 | 6000 | ... | null || 2 | 9000 | null | null | ... | null || 3 | null | 10000 | null | ... | null |+------+-------------+-------------+-------------+-----+-------------+Explanation: The revenue from Apr to Dec is null.Note that the result table has 13 columns (1 for the department id + 12 for the months).
문제
피벗
답
SELECT id,
AVG(IF(month = 'Jan', revenue, NULL)) AS Jan_Revenue,
AVG(IF(month = 'Feb', revenue, NULL)) AS Feb_Revenue,
AVG(IF(month = 'Mar', revenue, NULL)) AS Mar_Revenue,
AVG(IF(month = 'Apr', revenue, NULL)) AS Apr_Revenue,
AVG(IF(month = 'May', revenue, NULL)) AS May_Revenue,
AVG(IF(month = 'Jun', revenue, NULL)) AS Jun_Revenue,
AVG(IF(month = 'Jul', revenue, NULL)) AS Jul_Revenue,
AVG(IF(month = 'Aug', revenue, NULL)) AS Aug_Revenue,
AVG(IF(month = 'Sep', revenue, NULL)) AS Sep_Revenue,
AVG(IF(month = 'Oct', revenue, NULL)) AS Oct_Revenue,
AVG(IF(month = 'Nov', revenue, NULL)) AS Nov_Revenue,
AVG(IF(month = 'Dec', revenue, NULL)) AS Dec_Revenue
FROM Department
GROUP BY id
ORDER BY id