|
| 1 | + |
| 2 | +Easy Leetcode 1179 |
| 3 | + |
| 4 | +tags: SQL, Database |
| 5 | + |
| 6 | +方法1: |
| 7 | +To everyone wondering why you need the SUM. |
| 8 | +Imagine you don't use the group by and run such query: |
| 9 | + |
| 10 | +``` |
| 11 | +SELECT id, |
| 12 | +CASE WHEN month = "Jan" THEN revenue END as "Jan_Revenue", |
| 13 | +CASE WHEN month = "Feb" THEN revenue END AS "Feb_Revenue" |
| 14 | +FROM Department; |
| 15 | +
|
| 16 | +``` |
| 17 | + |
| 18 | +this will return multiple rows for each id + month pair: |
| 19 | + |
| 20 | +``` |
| 21 | ++----+-------------+-------------+ |
| 22 | +| id | Jan_Revenue | Feb_Revenue | |
| 23 | ++----+-------------+-------------+ |
| 24 | +| 1 | NULL | 7000 | |
| 25 | +| 1 | 8000 | NULL | |
| 26 | +| 1 | NULL | NULL | |
| 27 | +| 2 | 9000 | NULL | |
| 28 | +| 3 | NULL | 10000 | |
| 29 | ++----+-------------+-------------+ |
| 30 | +
|
| 31 | +
|
| 32 | +``` |
| 33 | + |
| 34 | +To get one row for each id we need to aggregate by id using GROUP BY. |
| 35 | + |
| 36 | + |
| 37 | +``` |
| 38 | +
|
| 39 | +/* |
| 40 | +方法1 |
| 41 | +*/ |
| 42 | +``` |
| 43 | +select id, |
| 44 | + sum(case when month = 'jan' then revenue else null end) as Jan_Revenue, |
| 45 | + sum(case when month = 'feb' then revenue else null end) as Feb_Revenue, |
| 46 | + sum(case when month = 'mar' then revenue else null end) as Mar_Revenue, |
| 47 | + sum(case when month = 'apr' then revenue else null end) as Apr_Revenue, |
| 48 | + sum(case when month = 'may' then revenue else null end) as May_Revenue, |
| 49 | + sum(case when month = 'jun' then revenue else null end) as Jun_Revenue, |
| 50 | + sum(case when month = 'jul' then revenue else null end) as Jul_Revenue, |
| 51 | + sum(case when month = 'aug' then revenue else null end) as Aug_Revenue, |
| 52 | + sum(case when month = 'sep' then revenue else null end) as Sep_Revenue, |
| 53 | + sum(case when month = 'oct' then revenue else null end) as Oct_Revenue, |
| 54 | + sum(case when month = 'nov' then revenue else null end) as Nov_Revenue, |
| 55 | + sum(case when month = 'dec' then revenue else null end) as Dec_Revenue |
| 56 | +from department |
| 57 | +group by id |
| 58 | +order by id |
| 59 | + |
| 60 | +``` |
| 61 | +
|
| 62 | +
|
| 63 | +
|
| 64 | +
|
| 65 | +
|
0 commit comments