需要查询才能按月查找连续订单

时间:2012-10-09 12:35:31

标签: mysql aggregate-functions mysql-5.5

我在编写此查询时遇到问题。

我需要获得连续几个月发货的当前订单数量。

示例:如果当前月份是11月,并且他们在7月,8月,9月,10月,11月下订单,则该用户将返回5。如果他们没有在11月下订单,它将返回0,因为他们的连胜被打破。

我关注的表格是customerorderdate

2 个答案:

答案 0 :(得分:0)

Here you replace now and static date as per columnname :

select (case 
       when (month(now())=11 and 
            (month('2012-02-02')>=7 and month('2012-02-02')<=11)) 
       then 5 
       else
       0 end) as 'month'
       from tablename

答案 1 :(得分:0)

使用日期表和客户表之间的交叉连接为每个客户/月份组合获取一行,然后在订单表中保持连接以获取详细信息,使用group by获取计数。

像这样的东西,虽然你需要修改它来处理列名是保留字。

SELECT customer.name, month.name, COUNT(order.id)
FROM customer
CROSS JOIN date
LEFT OUTER JOIN order
ON customer.id = order.customer_id
AND MONTH(date.date) = MONTH(order.date)
WHERE date.date BETWEEN startofdaterange AND endofdaterange
GROUP BY customer.name, month.name

或者,如果我误读了这个问题,如果他们每个月都在这个范围内订购,那么你需要一个订单的计数,如果他们跳过一个月就需要0,那么这样的事情(没有经过测试,所以期望输入错字或2,需要表def来测试): -

SELECT name, CASE  WHEN MonthCount = MonthOrderCount THEN OrderCount ELSE 0 END AS ContinuousOrderMonths
FROM (
SELECT CustName, COUNT(MonthName) AS MonthCount, SUM(MonthOrderCount) AS OrderCount, SUM(CASE WHEN MonthOrderCount > 0 THEN 1 ELSE 0 END)
FROM (
SELECT customer.name AS CustName, month.name AS MonthName, COUNT(order.id) AS MonthOrderCount
FROM customer
CROSS JOIN date
LEFT OUTER JOIN order
ON customer.id = order.customer_id
AND MONTH(date.date) = MONTH(order.date)
WHERE date.date BETWEEN startofdaterange AND endofdaterange
GROUP BY customer.name, month.name )Sub1 ) Sub2
GROUP BY CustName

如果您想要每月的客户列表和逗号分隔的订单列表: -

SELECT CustName, GROUP_CONCAT(CAST(MonthsOrder AS CHAR))
FROM (
SELECT customer.name AS CustName, month.name, COUNT(order.id) AS MonthsOrder
FROM customer
CROSS JOIN date
LEFT OUTER JOIN order
ON customer.id = order.customer_id
AND MONTH(date.date) = MONTH(order.date)
WHERE date.date BETWEEN startofdaterange AND endofdaterange
GROUP BY customer.name, month.name) Sub1
GROUP BY CustName

您可能需要展开此选项以获取每个月份的月份名称并强制执行订单