我在mySQL
数据库中有两个表
Table 1 [Orders]
DateOpened (date),
revenue
Table 2 [Movements]
DateStarted (date),
DateStopped (date)
对于任何给定日期,表1中可能有0个或更多条目,对于表2,DateStarted
或DateStopped
可能有0个或更多条目(DateStarted和DateStopped都可以是相同天或不同)
我想查询这些表的日期范围(例如:一个月),并获得每个日期的结果集,其中包含此表单中的某些数据:
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
CREATE TABLE IF NOT NOT EXISTS bb_movement
(
movementid
int(10)unsigned NOT NULL AUTO_INCREMENT,
orderid
int(10)unsigned NOT NULL COMMENT
dropoffdate
日期非空,
pickupdate
日期非空)
CREATE TABLE IF NOT NOT EXISTS bb_order
(
orderid
int(10)unsigned NOT NULL AUTO_INCREMENT,
movementid
int(10)unsigned NOT NULL,
dateopened
日期非空,
order_amount
浮动NOT NULL DEFAULT'0'
}
答案 0 :(得分: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