SQL -通过除以另一个字段的频率作为比例输出的字段



我试图为网站用户数据显示一个'比例'字段,其中比例将是衡量某个数据源对其转换贡献的程度(无论这可能是什么,它都是无关紧要的)。

这是我希望用SQL实现的输出:

Month  | ID | Country | Data Source |Proportion
Jan-15 | 1  | UK      |   GA        |    0.5
Jan-15 | 1  | UK      |   Omniture  |    0.5
Jan-15 | 2  | France  |   GA        |     1
Jan-15 | 3  | Germany |   GA        |    0.25
Jan-15 | 3  | Germany |   Omniture  |    0.25
Jan-15 | 3  | Germany |   Email     |    0.25
Jan-15 | 3  | Germany |   Moz       |    0.25
Feb-15 | 1  | UK      |   GA        |    0.5
Feb-15 | 1  | UK      |   Omniture  |    0.5
Feb-15 | 2  | France  |   Omniture  |    0.5
Feb-15 | 2  | France  |   GA        |    0.5
Feb-15 | 3  | Germany |   Omniture  |    0.33
Feb-15 | 3  | Germany |   Email     |    0.33
Feb-15 | 3  | Germany |   Moz       |    0.33
Mar-15 | 1  | UK      |   Omniture  |    0.5
Mar-15 | 1  | UK      |   GA        |    0.5
Mar-15 | 2  | France  |   Omniture  |    0.5
Mar-15 | 2  | France  |   Email     |    0.5

这是我目前正在工作和失败的SQL:

SELECT
    MONTH(registrationDate), country, DataSource, 1/COUNT(ID)
FROM
    data_table
WHERE
    registrationDate IS NOT NULL
GROUP BY
    MONTH(registrationDate), ID

这只是给出了比例的一个实例。使用上面的示例,一月份ID为1的用户将只有一条ratio = 0.5的记录。

在显示数据源之间正确共享的比例值的任何帮助将非常感激!

您需要将结果与原始数据结合起来。下面是使用JOIN的方法:

SELECT dt.*, ddt.value
FROM data_table dt JOIN
     (SELECT MONTH(registrationDate) as mon, ID, 
             1.0/COUNT(applicantId) as value
      FROM data_table
      WHERE registrationDate IS NOT NULL
      GROUP BY MONTH(registrationDate), ID
     ) ddt
     ON ddt.id = dt.id AND 
        ddt.mon = MONTH(dt.registrationDate);

你的问题中有ID, ApplicationIdRegistrationId。我不知道该用哪一列

编辑:

包括年份(这在任何情况下都是个好主意):

SELECT dt.*, ddt.value
FROM data_table dt JOIN
     (SELECT YEAR(registrationDate) as yyyy, MONTH(registrationDate) as mon, ID, 
             1.0/COUNT(applicantId) as value
      FROM data_table
      WHERE registrationDate IS NOT NULL
      GROUP BY YEAR(registrationDate), MONTH(registrationDate), ID
     ) ddt
     ON ddt.id = dt.id AND 
        ddt.mon = MONTH(dt.registrationDate) AND
        ddt.yyyy = YEAR(dt.registrationDate);

最新更新