2017-02-14 88 views
1

我必須從MySQL數據庫獲取一些統計數據,我需要獲取訂單數量範圍內的訂單數量,然後我需要按照週數進行分組,表created_at在訂單按價格範圍計數訂單,並按星期編號

我希望這是有道理的。

這是我能夠想出來的,但我在高級MySQL方面的經驗很少。

SELECT 
    x.Kurv, COALESCE(ordre, 0) AS ordre 
FROM (
    SELECT "0 - 100" AS Kurv 
    UNION SELECT "100 - 200" 
    UNION SELECT "200 - 300" 
    UNION SELECT "300 - 400" 
    UNION SELECT "400 - 500" 
    UNION SELECT "500 - 600" 
    UNION SELECT "over 600") x 
LEFT JOIN 
    (SELECT 
    CASE when base_total_ex_tax >= 0 and base_total_ex_tax <= 100 then "0 - 100" 
     when base_total_ex_tax > 100 and base_total_ex_tax <= 200 then "100 - 200" 
     when base_total_ex_tax > 200 and base_total_ex_tax <= 300 then "200 - 300" 
     when base_total_ex_tax > 300 and base_total_ex_tax <= 400 then "300 - 400" 
     when base_total_ex_tax > 400 and base_total_ex_tax <= 500 then "400 - 500" 
     when base_total_ex_tax > 500 and base_total_ex_tax <= 600 then "500 - 600" 
     else "over 600" 
    END AS Kurv, 
    COUNT(*) as ordre 
FROM orders 
WHERE 
    created_at > '2017-01-01 00:00:00' 
    && 
    status_id != 'canceled' 
GROUP BY 1) 
    y ON x.Kurv = y.Kurv 

哪個輸出的範圍和順序罰款,我只需要添加星期組。

在此先感謝。

回答

1

您可以找到本週CONCAT(YEAR(date), '/', WEEK(date))。然後,你可以在這組:

SELECT CONCAT(YEAR(date), '/', WEEK(date)) as wk 
,  CASE 
     WHEN amount <= 100 THEN '0 - 100' 
     WHEN amount <= 200 THEN '100 - 200' 
     ELSE '> 200' 
     END as kurve 
,  COUNT(*) 
FROM orderstable 
GROUP BY 
     wk 
,  kurve 

Example at rextester.

如果要列出所有kurves和幾個星期,甚至那些沒有訂單,您可以添加所有kurves(如您已完成)和all weeks到左連接的右側。客戶端通常比較容易。

+0

這就像一個魅力! :-) 謝謝。 – RK4002

0

希望,我正確理解你的問題。

請檢查下面的查詢

 SELECT 
    Y.WEEK_VAL , x.Kurv, COALESCE(ordre, 0) AS ordre 
FROM (
    SELECT "0 - 100" AS Kurv 
    UNION SELECT "100 - 200" 
    UNION SELECT "200 - 300" 
    UNION SELECT "300 - 400" 
    UNION SELECT "400 - 500" 
    UNION SELECT "500 - 600" 
    UNION SELECT "over 600") x 
LEFT JOIN 
    (SELECT WEEK(created_at) WEEK_VAL, 
    CASE when 5 >= 0 and 5 <= 100 then "0 - 100" 
     when 5 > 100 and 5 <= 200 then "100 - 200" 
     when 5 > 200 and 5 <= 300 then "200 - 300" 
     when 5 > 300 and 5 <= 400 then "300 - 400" 
     when 5 > 400 and 5 <= 500 then "400 - 500" 
     when 5 > 500 and 5 <= 600 then "500 - 600" 
     else "over 600" 
    END AS Kurv, 
    COUNT(*) as ordre 
FROM orders GROUP BY WEEK(created_at) , CASE when 5 >= 0 and 5 <= 100 then "0 - 100" 
     when 5 > 100 and 5 <= 200 then "100 - 200" 
     when 5 > 200 and 5 <= 300 then "200 - 300" 
     when 5 > 300 and 5 <= 400 then "300 - 400" 
     when 5 > 400 and 5 <= 500 then "400 - 500" 
     when 5 > 500 and 5 <= 600 then "500 - 600" 
     else "over 600" 
    END) 
    y ON x.Kurv = y.Kurv 
+0

我認爲你相信,但是我得到一個錯誤: SQL-錯誤(1054)字段列表中的未知列'Y.WEEK_VAL'。 謝謝你的快速回復! :-) – RK4002

+0

你能夠運行內部查詢「Y」嗎?請確認。 – Tajinder

+0

我也無法做到這一點,但它可能是我,沒有足夠的經驗。 :-O – RK4002