如何将sql查询的结果输出到报表中?

w7t8yxp5  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(282)

这个问题在这里已经有答案了

多个查询同一个表但在不同的列中mysql(4个答案)
两年前关门了。
我在以下表字段中有一个名称:

Invitations (user_id, type, created_at, completed_at)

我现在可以通过运行下面的查询并手动计算来获取上周的邀请会话速率。

SELECT * 
FROM invitations
WHERE created_at >= curdate() - INTERVAL DAYOFWEEK(curdate())+6 DAY
AND created_at < curdate() - INTERVAL DAYOFWEEK(curdate())-1 DAY
AND user_id != 1
AND type = 'email'
ORDER BY completed_at, created_at

sql是否可以输出更多的报表。。。回报的东西:

LAST WEEK | Total Invitations | Invitations Completed | % Conversion    
          | 100               | 50                    | 50%  
TWO WEEKS | Total Invitations | Invitations Completed | % Conversion    
          | 100               | 60                    | 60%

这样的事情在sql中是可能的还是我需要用应用程序逻辑来创建它?

kyxcudwk

kyxcudwk1#

也许你想用 count() 做一个 UNION ALL .

SELECT 'LAST WEEK' `Period`,
       count(created_at) `Total Invitations`,
       count(completed_at) `Invitations completed`,
       concat(count(completed_at) / count(created_at) * 100, '%') `% Conversion` 
       FROM invitations
       WHERE created_at >= curdate() - INTERVAL dayofweek(curdate()) + 6 DAY
             AND created_at < curdate() - INTERVAL dayofweek(curdate()) - 1 DAY
             AND user_id <> 1
             AND type = 'email'
UNION ALL
SELECT 'TWO WEEKS' `Period`,
       count(created_at) `Total Invitations`,
       count(completed_at) `Invitations completed`,
       concat(count(completed_at) / count(created_at) * 100, '%') `% Conversion` 
       FROM invitations
       WHERE created_at >= curdate() - INTERVAL dayofweek(curdate()) + 13 DAY
             AND created_at < curdate() - INTERVAL dayofweek(curdate()) - 1 DAY
             AND user_id <> 1
             AND type = 'email';
``` `count(completed_at)` 只计算行,其中 `completed_at` 不是null。我想 `completed_at` 当且仅当邀请未完成时为空。 `count(created_at)` 工作模拟。但我假设该列中没有空值(如果是空值,那么这些行将与 `WHERE` 子句,所以它们甚至不是计数的候选对象)。 `UNION ALL` 只需将两个结果集统一起来(而不消除重复的结果集,因为至少 `Period` 不同)。

相关问题