MYSQL 查询按自定义月份日期分组?
我编写了一个返回月销售额的查询。
SELECT
count(O.orderid) as Number_of_Orders,
concat (MonthName(FROM_UNIXTIME(O.`date`)),' - ',year(FROM_UNIXTIME(O.date))) as Ordered_Month,
sum(O.total) as TotalAmount,
Month(FROM_UNIXTIME(O.`date`)) as Month_of_Year,
year(FROM_UNIXTIME(O.date)) as Sale_Year
FROM orders O
group by Month_of_Year, Sale_Year
order by Sale_Year DESC,Month_of_Year DESC
我想将其分组为自定义日期,例如,
而不是 1 日到 1 日,它应该分组为每个月的 10 日 -10 日。 不知道如何以这种方式分组!
I wrote a query that returns monthly sales.
SELECT
count(O.orderid) as Number_of_Orders,
concat (MonthName(FROM_UNIXTIME(O.`date`)),' - ',year(FROM_UNIXTIME(O.date))) as Ordered_Month,
sum(O.total) as TotalAmount,
Month(FROM_UNIXTIME(O.`date`)) as Month_of_Year,
year(FROM_UNIXTIME(O.date)) as Sale_Year
FROM orders O
group by Month_of_Year, Sale_Year
order by Sale_Year DESC,Month_of_Year DESC
I would like to make it group for a custom date like
instead of 1st to 1st, it should group for 10th -10th of every month.
Not sure how to group it that way!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
因为你正在处理时间“转变”,所以你必须在方程中进行数学计算才能“伪造它”。所以
,本质上,您要获取日期,例如:3 月 11 日至 31 日 + 4 月 1 日至 10 日,并从中减去“10 天”...因此对于查询,它们将类似于 3 月 1 日至 31 日和 4 月11-30 会出现在每年的其余时间,如 4 月 1-20 日 + 5 月,依此类推......
because you are dealing with a time "shift", you'll have to do that math in your equation to "fake it out". Something like
So, in essence, you are taking the dates ex: March 11-31 + April 1-10 and subtracting "10 days" from them... so for the query, they will look like March 1-31, and April 11-30 will appear like April 1-20 + May, etc for rest of each year...
未测试。
这是一个更好的主意,可以避免有 4 个组,但只有 3 个组,
请根据您的需求进行调整。
Not tested.
This is a better idea in order to avoid having 4 groups but just 3
Adapt it to your needs.