0

mySQL我在数据库中有两个表

Table 1 [Orders]
DateOpened (date), 
revenue

Table 2 [Movements]
DateStarted (date), 
DateStopped (date)

对于任何给定的日期,表 1 中可能有 0 个或多个条目,对于表 2,两者DateStartedDateStopped(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_movementmovementidint(10) unsigned NOT NULL AUTO_INCREMENT, orderidint(10) unsigned NOT NULL COMMENT dropoffdatedate NOT NULL, pickupdatedate NOT NULL)

如果不存在则创建表bb_orderorderidint(10) unsigned NOT NULL AUTO_INCREMENT, movementidint(10) unsigned NOT NULL, dateopeneddate NOT NULL, order_amountfloat NOT NULL DEFAULT '0' }

4

1 回答 1

2

已解决:它需要在主选择中将源表与适当的聚合函数联合起来

 SELECT mv_date, sum(mv_count), sum(order_count), sum(order_revenue)
FROM (
    select dateopened as mv_date, 0 as mv_count, count(*) as order_count, sum(order_amount) as order_revenue
    from bb_order
    where (dateopened >= '2013-01-01' and dateopened <= '2013-06-30')
    group by mv_date
    union all
    SELECT dropoffdate AS mv_date, COUNT( * ) AS mv_count, 0 as order_count, 0 as order_revenue
    FROM bb_movement
    WHERE (dropoffdate >=  '2013-01-01' AND dropoffdate <=  '2013-06-30')
    group by mv_date
    UNION  all
    SELECT pickupdate AS mv_date, COUNT( * ) AS mv_count, 0 as order_count, 0 as order_revenue
    FROM bb_movement
    WHERE (pickupdate >=  '2013-01-01' AND pickupdate <=  '2013-06-30')
    group by mv_date
 ) mv
group by mv_date
order by mv_date
于 2013-06-28T07:27:13.730 回答