选择两个时间段的重复访客

时间:2014-04-21 14:46:52

标签: sql

我想找到我网站重复访问者的百分比。目前我选择用户一个月并将该月除以下个月。计算那些已经返回的人。这是编写该查询的最佳方式吗?

它产生的结果看似准确,但想知道是否有更优雅的解决方案。

SELECT (
SELECT COUNT(table.user) as Total
FROM table
WHERE table.event IN ('event1','event2','event3')
AND table.month IN ('october')
) /
(
SELECT COUNT(table.user) as newTotal
FROM table
WHERE table.event IN ('event1','event2','event3')
AND (table.month IN ('october') OR table.month IN ('november'))
) AS percent_return

表结构如下所示,您有相同的用户在同一个月或同一时间段内购买多个事件。

 order_number user month event gross

   1 jack october event2 30
   2 jack november event3 20
   3 jack november event3 20
   4 jack november event2 30
   5 sam november event2 30
   6 john october event3 20
   7 john october non_event 20

1 个答案:

答案 0 :(得分:1)

您不需要两个子查询来执行您想要的操作。只需使用条件聚合:

SELECT (SUM(s.month IN (october)) / SUM(s.month IN (october, november))
       ) as percent_return
FROM sales s
WHERE s.event IN ('event1', 'event2', 'event3') AND
      s.gross > 0;

此外,数字常量周围不需要单引号。