使用根据日期

时间:2016-12-09 00:03:55

标签: mysql sql syntax

尝试找到运行具有按天计数的查询的最佳方式,以及具有最近x天计数的列,但它变得更加复杂,然后我才意识到。

我正在尝试以下方面:

SELECT
date(created_at),
count(DISTINCT(user_id)) AS daily_users,
count(
    DISTINCT (
        CASE
        WHEN date(created_at) BETWEEN date_sub(created_at, INTERVAL 2 DAY)
        AND created_at THEN
            user_id
        END
    )
) AS users_2_day_lookback
FROM
table.users
WHERE
date(created_at) BETWEEN 'yyyy-mm-dd'
AND now()
GROUP BY
1

但是为期2天的回顾专栏没有回来。我有一种感觉,这应该通过某种涉及自联接的外部查询来完成,但我不确定那种语法会是什么样子。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

逐日查询:

select date(created_at),
       count(distinct user_id) as daily_users
from table.users u
group by date(created_at);

为期两天的回顾是这样的:

select dte, daily_users,
       (select count(distinct u2.user_id)
        from table.users u2
        where u2.created_at >= date_sub(dte, interval 2 days) and
              u2.created_at < date_add(dte, interval 1 day)
       ) as users_2_day_lookback
from (select date(created_at) as dte,
             count(distinct user_id) as daily_users
      from table.users u
      group by date(created_at)
      ) u;

此查询解释&#34; 2天回顾&#34;作为当天加上前两天。更改替代定义的where条件非常容易。