mysql合并报表的多个查询

zz2j4svz  于 2021-06-15  发布在  Mysql
关注(0)|答案(0)|浏览(266)

请参见此处的sqlfiddle:http://sqlfiddle.com/#!9月9日BB273
我需要在3个查询中创建一个报告。它需要是没有子查询的单个查询(由于orm的限制)。
主要查询是:

SELECT SQL_CALC_FOUND_ROWS 
Organization.name as organization_name, 
Program.unique_id as program_uuid, 
Program.name as program_name,
Program.start_date,
Program.end_date,
Program.grace_period,
'Placeholder A' as 'Participant Count',
'Placeholder B' as 'Total Participant Points',
count(distinct Transaction.id) as 'Transaction Count',
sum(TransactionItem.quantity) as 'Total Redemptions',
sum(((TransactionProduct.retail + IFNULL(TransactionProduct.shipping,0) + IFNULL(TransactionProduct.handling,0)) * TransactionItem.quantity)) as 'Total'
FROM `TransactionItem` 
JOIN `Transaction` ON `Transaction`.id = `TransactionItem`.transaction_id 
JOIN `TransactionProduct` ON `TransactionItem`.reference_id = `TransactionProduct`.reference_id 
JOIN `Participant` ON `Transaction`.participant_id = `Participant`.id 
JOIN `Program` ON `Program`.id = `Participant`.program_id 
JOIN `Organization` ON `Organization`.id = `Participant`.organization_id 
WHERE 1=1  
AND `Organization`.`unique_id` = 'demo2' 
AND `Program`.`unique_id` = 'demo2' 
AND `Transaction`.`created_at` >= '2018-10-01 00:00:00' 
AND `Transaction`.`created_at` <= '2018-12-18 00:00:00';

如您所见,此报告适用于10/1和12/18之间的日期范围。组成报告的结果集是。。。

organization_name | program_uuid | program_name | start_date | end_date | grace_period | Participant Count | Total Participant Points | Transaction Count | Total Redemptions | Total
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Demo2 Org           demo2          Demo2          2018-10-01   2018-12-27  5             Placeholder A       Placeholder B              11                   92                 2853.13

如您所见,有两个数据点我无法从这个查询中获得。
(1) “demo2”计划的参与者总数。此查询获取该数据点。

/* Placeholder A */
select program_id, count(*) as 'Participant Count' from participant 
where active = 1
group by program_id;

退货:

program_id   |  Participant Count
----------------------------------
2               102

(2) 日期10/1和12/18之间所有行的调整金额之和。这个查询实现了这一点。

/* Placeholder B */
select sum(amount) as 'Total Particpant Points' from adjustment 
where participant_id in (select id from participant where program_id =2)
and type = 1
and created_at >= '2018-10-01 00:00:00' and created_at <= '2018-12-18 00:00:00';

退货:

Total Participant Points
 ------------------------
 10000.50000

有没有一种方法可以在一个查询中收集所有这些数据而无需子查询?

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题