0

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

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

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

我关心的表是customerorderdate

4

2 回答 2

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
于 2012-10-09T12:56:44.797 回答
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

或者,如果我误读了这个问题,并且如果他们每个月都在该范围内订购,则需要计算订单数量,或者如果他们跳过一个月,则需要计算订单数量,然后类似这样的事情(未经测试,因此预计有错字或 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

您可能需要扩展它以获取每个月份的名称并强制排序

于 2012-10-09T12:57:28.397 回答