mysql中case的一個例子
阿新 • • 發佈:2018-11-03
最近遇到一個問題:
year | amount | num |
---|---|---|
1991 | 1 | 1.1 |
1991 | 2 | 1.2 |
1991 | 3 | 1.3 |
1992 | 1 | 2.1 |
1992 | 2 | 2.2 |
1992 | 3 | 3.3 |
把上面表格的資料查詢成:
year | m1 | m2 | m3 |
---|---|---|---|
1991 | 1.1 | 1.2 | 1.3 |
1992 | 2.1 | 2.2 | 2.3 |
看到這樣的需求,首先想到的是用case去統計以及 用group by來分組
第一版sql程式碼:
SELECT `year`, (CASE WHEN amount = 1 THEN num END) AS n1, (CASE WHEN amount = 2 THEN num END) AS n2, (CASE WHEN amount = 3 THEN num END) AS n3 FROM testGROUP BY `year`
查詢出來的結果有點不如人意:
year | n1 | n2 | n3 |
---|---|---|---|
1991 | 1.1 | ||
1992 | 2.1 |
這麼說明了分組之後只顯示到第一行資料,那麼我們去掉分組看看:
SELECT `year`, (CASE WHEN amount = 1 THEN num END) ASn1, (CASE WHEN amount = 2 THEN num END) AS n2, (CASE WHEN amount = 3 THEN num END) AS n3 FROM test
year | n1 | n2 | n3 |
---|---|---|---|
1991 | 1.1 | ||
1991 | 1.2 | ||
1991 | 1.3 | ||
1992 | 2.1 | ||
1992 | 2.2 | ||
1992 | 2.3 |
有點像我們想要的了,只是沒有分組以及去掉空值
而且我們可以看出,在分組的情況下m1,m2,m3的值都是一個最大值來的
所以我們可以用一個子查詢來查詢上面的結果集中分組的最大值 最終版sql:
SELECT `year`, MAX(n1) AS m1, MAX(n2) AS m2, MAX(n3) AS m3 FROM ( SELECT `year`, (CASE WHEN amount = 1 THEN num END) AS n1, (CASE WHEN amount = 2 THEN num END) AS n2, (CASE WHEN amount = 3 THEN num END) AS n3 FROM test ) AS a GROUP BY `year`
最終可以得到我們想要的結果:
year | m1 | m2 | m3 |
---|---|---|---|
1991 | 1.1 | 1.2 | 1.3 |
1992 | 2.1 | 2.2 | 2.3 |