如何将来自一个 SQL 选择的聚合值除以来自另一个 SQL 选择的聚合值?
Posted
技术标签:
【中文标题】如何将来自一个 SQL 选择的聚合值除以来自另一个 SQL 选择的聚合值?【英文标题】:How to divide aggregated values from one SQL select by aggregated value from another SQL select? 【发布时间】:2018-11-28 17:55:32 【问题描述】:我想计算系统与多少客户通信。在问题的背景下,在小组的背景下,在节目的背景下,在该时期的渠道背景下,按百分比计算。
公式很简单:
F = X / Y
地点:
X - number of clients communicated by system.
和
Y - number of clients in analizing sample.
我有数据库表 INTERACTIONS。
表格示例:
datetime | Issue | Group | ProgramID | Channel | CustomerID | Outcome ---------------+-------+-------+-----------+---------+------------+-------- 20181126000001 | Sale | Loans | P-1 | SMS | 5 | Accept 20181126000005 | Sale | Loans | P-1 | PUSH | 7 | Ignore 20181126000010 | Sale | Loans | P-2 | SMS | 8 | Ignore 20181126000015 | Sale | Loans | P-3 | PUSH | 10 | Accept
所以 X 的选择是:
SELECT
ISSUE, GROUP, PROGRAMID, CHANNEL,
COUNT(DISTINCT CUSTOMERID) AS Customers
FROM INTERACTIONS
GROUP BY ISSUE, GROUP, PROGRAMID, CHANNEL
ORDER BY 1 ASC, 2 ASC, 3 ASC, 4 ASC;
Y 的选择是:
SELECT COUNT(DISTINCT CUSTOMERID) AS Customers
FROM INTERACTIONS;
如何结合这两个 SQL 选择并获得 F=X/Y 的报告?
我想得到类似的结果:
【问题讨论】:
【参考方案1】:SELECT
ISSUE, GROUP, PROGRAMID, CHANNEL,
COUNT(DISTINCT CUSTOMERID)/
(SELECT COUNT(DISTINCT CUSTOMERID) FROM
INTERACTIONS) AS Customers
FROM INTERACTIONS
GROUP BY ISSUE, GROUP, PROGRAMID, CHANNEL
ORDER BY 1 ASC, 2 ASC, 3 ASC, 4 ASC
只需将 Y 查询放在 X 查询中
【讨论】:
以上是关于如何将来自一个 SQL 选择的聚合值除以来自另一个 SQL 选择的聚合值?的主要内容,如果未能解决你的问题,请参考以下文章
Oracle PL/SQL 将游标(来自函数)中的每个值一一分配给另一个游标