我有以下架构: http://sqlfiddle.com/#!9/bd3a4/1 我想要 按日期分组()并添加user_id =? 每天计算每天的结果。 必填结果日| TotalRequests | TotalOrders
答案 0 :(得分:1)
由于您可以在第1天订购,并在第8天收到请求,因此您可能在一侧有条目而在另一侧没有。为了满足您的需求,我会按日期单独处理所有订单和请求的UNION。然后将这些值向上滚动。内部Pre-Aggregate结果查询是应用每个用户的WHERE子句的位置。预聚合查询还有一个recSource列,用于指示记录来自订单的“O”和来自请求的“R”,因此汇总知道分别存储总计数的列。
select
preAgg.recDate,
SUM( case when preAgg.recSource = 'O' then preAgg.recCount else 0 end ) as OrderCount,
SUM( case when preAgg.recSource = 'R' then preAgg.recCount else 0 end ) as RequestCount
from
( select
date(o.created_at) recDate,
'O' as recSource,
count(*) as recCount
from
orders o
where
o.user_id = 3
group by
date(o.created_at)
UNION ALL
select
date(r.created_at) recDate,
'R' as recSource,
count(*) as recCount
from
requests r
where
r.user_id = 3
group by
date(r.created_at) ) preAgg
group by
preAgg.recDate
order by
preAgg.recDate
对于查询优化,我会确保您的订单和请求表都有一个索引(user_id,created_at)。
答案 1 :(得分:0)
您可以使用以下查询:
SELECT
DATE(o.created_at) AS Day
,COUNT(r.id) AS TotalRequests
,COUNT(o.id) AS TotalOrders
FROM orders o
LEFT JOIN
requests r ON
r.id = o.request_id
WHERE o.user_id = 3
GROUP BY DATE(r.created_at), DATE(o.created_at),o.user_id