[英]How to sort results in MySQL right join?
我正在嘗試使用以下兩個表使用 MySQL 獲取全年的月度數據,
貸款
` +--------+--------+-------+----------+
| idloan | amount | tot | interest |
+--------+--------+-------+----------+
| 3 | 10000 | 15000 | 50 |
| 4 | 5000 | 6000 | 10 |
| 5 | 20000 | 30000 | 10 |
| 6 | 30000 | 3000 | 10 |
| 7 | 15000 | 16500 | 10 |
+--------+--------+-------+----------+ `
月
`+---------+-------+
| idmonth | month |
+---------+-------+
| 1 | 1 |
| 2 | 2 |
| 3 | 3 |
| 4 | 4 |
| 5 | 5 |
| 6 | 6 |
| 7 | 7 |
| 8 | 8 |
| 9 | 9 |
| 10 | 10 |
| 11 | 11 |
| 12 | 12 |
+---------+-------+ `
我使用這個查詢來獲取空閑貸款的數量、金額總和和每個月的總和,
` SELECT
m.month,
COUNT(l.idloan)AS m_count,
COALESCE(SUM(l.amount),0)AS amount,
COALESCE(SUM(l.total),0)AS total
FROM loan l RIGHT JOIN month m using(month)
GROUP BY m.month `
輸出是
` +-------+---------+--------+-------+
| month | m_count | amount | total |
+-------+---------+--------+-------+
| 1 | 0 | 0 | 0 |
| 10 | 1 | 15000 | 16500 |
| 11 | 1 | 30000 | 3000 |
| 12 | 3 | 35000 | 51000 |
| 2 | 0 | 0 | 0 |
| 3 | 0 | 0 | 0 |
| 4 | 0 | 0 | 0 |
| 5 | 0 | 0 | 0 |
| 6 | 0 | 0 | 0 |
| 7 | 0 | 0 | 0 |
| 8 | 0 | 0 | 0 |
| 9 | 0 | 0 | 0 |
+-------+---------+--------+-------+ `
我的問題是如何排序以得到這樣的輸出
` +-------+---------+--------+-------+
| month | m_count | amount | total |
+-------+---------+--------+-------+
| 1 | 0 | 0 | 0 |
| 2 | 0 | 0 | 0 |
| 3 | 0 | 0 | 0 |
| 4 | 0 | 0 | 0 |
| 5 | 0 | 0 | 0 |
| 6 | 0 | 0 | 0 |
| 7 | 0 | 0 | 0 |
| 8 | 0 | 0 | 0 |
| 9 | 0 | 0 | 0 |
| 10 | 1 | 15000 | 16500 |
| 11 | 1 | 30000 | 3000 |
| 12 | 3 | 35000 | 51000 |
+-------+---------+--------+-------+ `
我相信你只需要一個 order by 條款。 所以你的查詢應該是
SELECT
m.month,
COUNT(l.idloan)AS m_count,
COALESCE(SUM(l.amount),0)AS amount,
COALESCE(SUM(l.total),0)AS total
FROM loan l RIGHT JOIN month m using(month)
GROUP BY m.month
ORDER BY CONVERT(m.month,UNSIGNED INTEGER)
如果可能,您應該將月表的月列的數據類型更改為 INT。
無論如何,您仍然可以在 order by 子句中將字符串轉換/轉換為整數。
像下面這樣
SELECT m.month,
COUNT(l.idloan)AS m_count,
COALESCE(SUM(l.amount),0)AS amount,
COALESCE(SUM(l.total),0)AS total FROM loan l
RIGHT JOIN month m using(month) GROUP BY m.month
ORDER BY CONVERT(m.month,UNSIGNED INTEGER)
建議您更改數據類型,而不是在 order by 子句中使用CONVERT 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.