SQL

1179. Reformat Department Table

Write an SQL query to reformat the table such that there is a department id column and a revenue column for each month.

The query result format is in the following example:

Department table:
+------+---------+-------+
| id | revenue | month |
+------+---------+-------+
| 1 | 8000 | Jan |
| 2 | 9000 | Jan |
| 3 | 10000 | Feb |
| 1 | 7000 | Feb |
| 1 | 6000 | Mar |
+------+---------+-------+

Result table:
+------+-------------+-------------+-------------+-----+-------------+
| id | Jan_Revenue | Feb_Revenue | Mar_Revenue | ... | Dec_Revenue |
+------+-------------+-------------+-------------+-----+-------------+
| 1 | 8000 | 7000 | 6000 | ... | null |
| 2 | 9000 | null | null | ... | null |
| 3 | null | 10000 | null | ... | null |
+------+-------------+-------------+-------------+-----+-------------+

Note that the result table has 13 columns (1 for the department id + 12 for the months).

Logic: Use Case() function

LINK

--

--

--

My homepage to record my thought processes for solving SQL and Algorithm questions

Recommended from Medium

The Extentia Blog: Let’s Bake a Data Science Cake

Cold Hard Data Feelings

I part-time studied Data Science (M.Sc.) in 2021 — here is what it’s like

The Real-World Use Of Data

From Storytelling to Scrollytelling: A Short Introduction and Beyond*

“The Impatient List” by Gupta et al.

12 Excellent Datasets for Data Visualization in 2022

Data Analyst Project: Business Decision Research

The “Valley of Despair” and The “Way of Enlightenment”

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Isabelle

Isabelle

In love with telling stories with data

More from Medium

How to identify similarly pronounced words in SQL server?

Leetcode SQL

SQL IS EASY