One SQL interview question (row and column Interchange), SQL questions
There is a high probability that an SQL question will appear during the interview. Recently, some students will still encounter such a question during the interview. I would like to share with you here.
Question: The database has a table named sales as follows.
Year |
Quarter |
Sales Volume |
1991 |
1 |
11 |
1991 |
2 |
12 |
1991 |
3 |
13 |
1991 |
4 |
14 |
1992 |
1 |
21 |
1992 |
2 |
22 |
1992 |
3 |
23 |
1992 |
4 |
24 |
Requirement: Write an SQL statement to query the result as follows.
Year |
First Quarter |
Quarter 2 |
Quarter 3 |
Fourth Quarter |
1991 |
11 |
12 |
13 |
14 |
1992 |
21 |
22 |
23 |
24 |
The answer is as follows:
Select Year, sum (case when quarter = 1 then sales else 0 end) as First Quarter, sum (case when quarter = 2 then sales else 0 end) as second quarter, sum (case when quarter = 3 then sales else 0 end) as three quarter, sum (case when quarter = 4 then sales else 0 end) as four quarter from sales group by year;