[英]SQL query calculate and display sum data per each of the past 12 months
[英]SQL query calculate and display sum data per each month of the year
我有一些數據的“訂單”表,如下所示:
--------------------------------- id | amount | order_date --------------------------------- 1 | 100.00 | 2018-03-12 2 | 120.00 | 2018-03-25 3 | 200.00 | 2018-04-10 4 | 250.00 | 2018-04-20 5 | 300.00 | 2018-05-02
我想顯示當前年份每個月的SUM('amount'),我想稍后使用此數據創建圖表。
我想要達到這樣的結果。
--------------------------------- month | sum(amount) --------------------------------- January | 0.00 February | 0.00 March | 320.00 April | 450.00 Mai | 300.00 June | 0.00 July | 0.00 August | 0.00 September | 0.00 October | 0.00 November | 0.00 December | 0.00
我創建了一個單獨的表“ months”,其中包含一年中的所有月份,然后我將其與“ orders”保留在一起,但沒有用,這是我使用的查詢。
請幫忙。
SELECT months.month, IFNULL( sum(orders.amount), 0 ) AS amount
FROM months
LEFT OUTER JOIN orders ON month(orders.order_date) = months.month
GROUP BY months.month
最后我使它工作這是我的查詢
SELECT IFNULL( sum(orders.amount), 0 ) AS amount FROM months LEFT OUTER JOIN orders ON monthName(orders.order_date) = months.month GROUP BY months.month Order BY FIELD(MONTH,'January','February','March','April', 'May', 'June', 'Jully', 'August', 'September', 'October', 'November', 'December')
month()函數返回一個數字,而不是月份的名稱。
使用monthname()函數或將月份的數字(而不是月份的名稱)存儲在助手表中。 后者稍微可靠一些,因為mysql的語言設置會影響monthname()函數的返回值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.