1

假设有一个activities包含两列的表:字符串actioncreated_at时间戳。并且在 action 列中只有两个可能的值visitor signup

我想查看每天每次访问的注册百分比。喜欢:

Date       |  Conversion
--------------------------
2013-01-01 |  30%
2013-01-02 |  27%
2013-01-03 |  15%
2013-01-04 |  22%

是否可以使用单个 SQL 查询?

4

2 回答 2

1

对于 SQL 服务器,这应该可以工作:

SELECT coalesce(v.y, s.y) y, coalesce(v.m, s.m) m, coalesce(v.d, s.d) d, 
    100.0 * isnull(s.num, 0) / (isnull(s.num, 0) + isnull(v.num, 0)) conversion  
FROM
(
    SELECT datepart(YEAR, [date]) y, datepart(m, [date]) m,datepart(d, [date]) d, 
        count(action) num
    FROM actions
    WHERE action = 'visit'
    GROUP BY datepart(YEAR, [date]), datepart(m, [date]), datepart(d, [date])
) v
FULL OUTER JOIN
(
    SELECT datepart(YEAR, [date]) y, datepart(m, [date]) m,datepart(d, [date]) d, 
        count(action) num
    FROM actions
    WHERE action = 'signup'
    GROUP BY datepart(YEAR, [date]), datepart(m, [date]), datepart(d, [date])
) s
ON v.y = s.y AND v.m = s.m AND v.d = s.d

我将字符串连接、舍入和一般鲁棒性作为练习留给你。

于 2013-10-03T12:23:36.317 回答
0

如果这是 SQL Server 2005+,您可以尝试以下方法:

SELECT
  Date,
  Conversion = signup * 100.0 / (signup + visit)
FROM (
  SELECT
    Date = DATEADD(DAY, DATEDIFF(DAY, 0, created_at), 0),
    action
  FROM activities
) AS a
PIVOT (
  COUNT(action) FOR action IN (visit, signup)
) AS p
;

Date表达式将created_at时间戳从时间部分中剥离出来。在 SQL Server 2008 及更高版本中,可以将其替换为更清洁、更高效的date类型转换操作:

Date = CAST(created_at AS date)
于 2013-10-03T16:21:32.000 回答