将两个查询与计数函数组合为一个结果集

Posted

技术标签:

【中文标题】将两个查询与计数函数组合为一个结果集【英文标题】:Combine two queries with count function for a single result set 【发布时间】:2013-06-27 13:14:43 【问题描述】:

我在 mysql 数据库中有两个表

Table 1 [Orders]
DateOpened (date), 
revenue

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

对于任何给定日期,表 1 中可能有 0 个或多个条目,对于表 2,DateStartedDateStopped 可能有 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

如果不存在则创建表 bb_movement ( movementid int(10) 无符号非空 AUTO_INCREMENT, orderid int(10) 无符号非空注释 dropoffdate 日期不为空, pickupdate日期不为空)

如果不存在则创建表bb_order ( orderid int(10) 无符号非空 AUTO_INCREMENT, movementid int(10) 无符号非空, dateopened 日期不为空, order_amount float NOT NULL DEFAULT '0'

【问题讨论】:

Desc table bb_movement and bb_order 以及您真正想要实现的目标。 我已经在正文中显示了我想要实现的目标 - 对于我指定范围内的每个日期,当存在 1 个或多个订单(订单数和这些匹配订单的收入)或移动计数(匹配 dropoffdate 或 pickupdate 或两者)。 表 bb_movement 和 bb_order 的列是什么 就这个问题而言,我认为以上内容就足够了,不是吗?我将编辑主要问题并添加 【参考方案1】:

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

 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

【讨论】:

以上是关于将两个查询与计数函数组合为一个结果集的主要内容,如果未能解决你的问题,请参考以下文章

获取 dapper.QueryMultiple 方法返回的结果集计数

Python 常用内置函数 二

Django通过谓词和计数结果注释查询集

有没有办法获取带有结果集的 JPA 命名查询的计数大小?

如何将来自不同查询的值(计数)组合成一个查询

excel如何实现一对多查询