mySQL
我在数据库中有两个表
Table 1 [Orders]
DateOpened (date),
revenue
Table 2 [Movements]
DateStarted (date),
DateStopped (date)
对于任何给定的日期,表 1 中可能有 0 个或多个条目,对于表 2,两者DateStarted
或DateStopped
(DateStarted 和 DateStopped 可能是同一天或不同)可能有 0 个或多个条目
我想查询这些表的日期范围(例如:一个月)并为每个具有这种形式的数据的日期获取结果集:
date, sum(revenue), num_orders (count of orders for the date), num_movements (count of movements for the date)
我创建了两个单独的查询来完成每个部分,但我不知道如何将它们组合起来,这样我就可以实现一个高效的查询,而不必在代码中合并结果集。我似乎被挂断的事情是 count() 函数正确应用。
以下是有效的现有查询:
select count(*) as total_movements, movement_date
from (
select dropoffdate as movement_date
from bb_movement
where (dropoffdate >= '2013-01-01' and dropoffdate <= '2013-06-30')
union all
select pickupdate as movement_date
from bb_movement
where (pickupdate >= '2013-01-01' and pickupdate <= '2013-06-30')
) as t3
group by movement_date
order by movement_date asc
select count(*) as num_orders, sum(order_amount) as revenue, dateopened as date_opened
from bb_order
where (dateopened >= '2013-01-01' and dateopened <= '2013-06-30')
group by dateopened
order by dateopened asc
如果不存在则创建表bb_movement
(
movementid
int(10) unsigned NOT NULL AUTO_INCREMENT,
orderid
int(10) unsigned NOT NULL COMMENT
dropoffdate
date NOT NULL,
pickupdate
date NOT NULL)
如果不存在则创建表bb_order
(
orderid
int(10) unsigned NOT NULL AUTO_INCREMENT,
movementid
int(10) unsigned NOT NULL,
dateopened
date NOT NULL,
order_amount
float NOT NULL DEFAULT '0' }