我必须从MySQL数据库中获取一些统计数据,我需要获得订单大小范围内的订单数量,然后我需要按照订单中的created_at表格中的WEEK进行分组
我希望这是有道理的。
这是我能够提出的,但我对高级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
哪个输出范围和订单很好,我只需要添加周组。
提前致谢。
答案 0 :(得分: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
如果您想列出所有kurves和周,即使是没有订单的人,也可以将所有kurves(如您已经完成的)和all weeks添加到左连接的右侧。这通常更容易做客户端。
答案 1 :(得分: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