我目前正在尝试获取过去30天的所有订单并返回总数和订单数量。如果一天没有订单,我仍然希望我的结果中有一行(显然有计数和总数== 0)。
有办法做到这一点吗?
有很多问题要求这个,而不需要总是得到30行。但是,我不能对它们发表评论,因为我的声誉太低了。
例如: selecting all orders for last 30 days, and counting how many per day
答案 0 :(得分:3)
天数生成器取自generate days from date range
另一项工作是简单的左连接到分组订单
(用左连接子查询中的表名和列名更改)
select a.Date, pr.orders_count, pr.price
from (
select curdate() - INTERVAL (a.a + (10 * b.a) + (100 * c.a)) DAY as Date
from (select 0 as a union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) as a
cross join (select 0 as a union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) as b
cross join (select 0 as a union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) as c
) a
left join (select order_time, count(*) as orders_count, sum(price) as price from orders group by order_time) pr
on a.Date = pr.order_time
where a.Date >= NOW() - INTERVAL 30 DAY
order by a.Date desc
答案 1 :(得分:1)
您可以使用日历表或日期维度。
select td.db_date, count(o.OrderId) as Orders
from time_dimension td
left join Orders o
on date(o.OrderDate) = db_date
where td.db_date >= date(adddate(curdate(), interval -30 day))
and td.db_date <= date(curdate())
group by td.db_date
MySQl日历表参考
答案 2 :(得分:0)
您可以将发布器用于Get a list of dates between two dates
的日期您可以在订单表中使用outter join。
答案 3 :(得分:0)
尝试 -
SELECT dateDuringPeriod, SUM( orderValue ), COUNT( orderID )
FROM
(
SELECT dateDuringPeriod,
IFNULL( orderID, 0 ) orderID,
IFNULL( orderValue, 0 ) orderValue
FROM
(
SELECT DATE_ADD( CURDATE(), INTERVAL singles + tens DAY) dateDuringPeriod
FROM
(
SELECT 0 singles
UNION ALL SELECT -1
UNION ALL SELECT -2
UNION ALL SELECT -3
UNION ALL SELECT -4
UNION ALL SELECT -5
UNION ALL SELECT -6
UNION ALL SELECT -7
UNION ALL SELECT -8
UNION ALL SELECT -9
) singles JOIN
(
SELECT 0 tens
UNION ALL SELECT -10
UNION ALL SELECT -20
) tens
) datesDuringPeriod LEFT JOIN
(
SELECT orderID,
DATE( orderDate ) orderDate,
orderValue
FROM tblOrders
) ordersWithoutTimes
ON datesDuringPeriod.dateDuringPeriod = ordersWithoutTimes.orderDate
) tblOrderSummary
GROUP BY dateDuringPeriod
ORDER BY dateDuringPeriod;
我创建了一个包含示例数据的示例表,发现此代码有效。