2017-09-29 57 views
-1

我想獲取特定年份的每個月的銷售數據,但我在爲其構建查詢時遇到問題。如何獲取每年每月的銷售數據

這裏是我試過

SELECT COUNT(`id`) AS `total_order` 
FROM orders 
WHERE date BETWEEN ? AND ? 
GROUP BY `total_order` 

這裏是我的表看起來怎麼樣

---------------------------------------- 
| id | item_name | amount | time  | 
| 21 | item_1 | 10  | 1506675630 | 
| 22 | item_2 | 30  | 1506675630 | 
| 23 | item_3 | 70  | 1506675630 | 
| 24 | item_4 | 100 | 1506675630 | 
---------------------------------------- 

現在,這裏是我從查詢

1 - Total Sales amount made from the beginning of the year till today. 
2 - Sales made Today 
3 - Sales made in Last Month 
4 - Sales Made in Last 3 month 
5 - Sales Made in Last 6 Month 
6 - Total Number of Sales made in every month of this particular year 

爲如要 - January - 20 Feb -100 March - 200如&等。

我該如何實現這個複雜的查詢?

+0

我發現此鏈接用於在日期中轉換數字數字:https://stackoverflow.com/questions/19271007/converting-a-numeric-value-to-date-time – Alberslash

+0

添加時間列,如@Alberslash的日期說 –

+2

我覺得你實際上是在尋求不同的querys。您無法在同一個查詢中表示不同的時間分組。此外,感覺就像你要求我們爲你查詢,你的嘗試甚至沒有接近它的樣子,我想知道它是否合乎邏輯。 – whiteTea

回答

0
SELECT `id` AS `Order_Number`, item_name, SUM(Amount) 
    FROM orders 
    WHERE time >= '01/01/17' 
    GROUP BY date 

這會給你你的第一個結果。嘗試別人,讓我知道你會得到什麼

+0

GROUP BY無效,將在舊版本的MySQL中返回不可預知的結果,將在新版本中引發錯誤(除非在)一般的GROUP BY規則說:如果指定了GROUP BY子句,SELECT列表中的每個列引用必須標識一個分組列或者是一個set函數的參數。 – jarlh

+0

當然,使用ORDER BY 1也可能無法預測,特別是在我的工作中。如果有人添加另一列,會發生什麼 –

+0

是的,ORDER BY序數位置在20多年前從ANSI SQL標準中刪除。 (並且GROUP BY序號位置從未在標準中。) – jarlh

0

這回答你的第一個問題

SELECT 
DATE_FORMAT(FROM_UNIXTIME(time), '%Y-%m') as interval, 
COUNT(*) AS sales_made, 
SUM(amount) AS sales_amount 
FROM orders 
WHERE 
time BETWEEN UNIX_TIMESTAMP('2017-01-01') AND UNIX_TIMESTAMP('2018-01-01') 
GROUP BY 1 
ORDER BY 1; 
+0

您的sql查詢中有錯誤 - 您的SQL語法中有錯誤;檢查與您的MySQL服務器版本相對應的手冊,以在'interval,COUNT(*)AS sales_made, –

+0

'附近使用'正確的語法'Interval'是一個保留字... – jarlh

0

這裏是我想會的工作:

的第5個查詢嘗試這樣的事情。

SELECT SUM(amount) 
    FROM orders 
    WHERE DATE_FORMAT(FROM_UNIXTIME(`orders.time`), '%Y-%m-%d') BETWEEN ? AND ? 

而最後一個,你將需要:

SELECT DATE_FORMAT(FROM_UNIXTIME(`orders.time`), '%Y-%m-%d') AS 'date', SUM(amount) 
     FROM orders 
     WHERE date between ? AND ? 
     GROUP BY DATE_FORMAT(date, '%Y%m') 

你可以嘗試沒有FROM_UNIXTIME,如果它不工作。