MYSQL按日期分组并计算第一个日期

时间:2019-07-13 09:18:05

标签: mysql sql

我要查询一个MySQL数据库,并从第N周注册的用户中查询user_id,signup_date和order_date列中,有多少人在N + 1,N + 2, N + 3 ...

这是我的查询,但是由于我相信它是如何分组的,所以在count(min())上失败了。

我的技能很有限,所以如果我偏离正轨,我会道歉

我尝试了不同的分组方式,但是我不太了解如何对日期进行分组,但仍然只计算第一个/最早的订单日期

SELECT 
signup_year, 
signup_week, 
COUNT(signup_date) AS "total_signups", 
order_year,
order_week,
SUM(orders) AS total_first_orders

FROM
(
SELECT
DATE_FORMAT(s.signup_timestamp, "%d/%m/%Y") AS signup_date,
YEAR(s.signup_timestamp) AS signup_year,
WEEK(s.signup_timestamp) AS signup_week,
YEAR(o.order_timestamp) AS order_year,
DATE_FORMAT(o.order_timestamp, "%d/%m/%Y") AS order_date,
WEEK(o.order_timestamp) AS order_week,
COUNT(MIN(o.order_timestamp)) AS orders

FROM signups s
INNER JOIN orders o ON s.user_id = o.user_id

GROUP BY o.user_id, YEAR(o.user_id),WEEK(o.user_id)

) X
GROUP BY signup_year ASC, signup_week ASC, order_year ASC, order_week ASC

我想知道在第N周注册的用户中的user_id,signup_date和order_date列中,有多少人在N + 1,N + 2,N + 3中下了第一笔订单... < / p>

2 个答案:

答案 0 :(得分:0)

您可以尝试使用子类之间的连接来进行符号和命令

    select t1.user_id, t1.y_sign, t1.m_sign, t1.w_sign, t1.num_sign, t2.w_first_ord
    from (
        select   o.user_id, year(s.signup_timestamp) y_sign, month(s.signup_timestamp) m_sign,  week(s.signup_timestamp) w_sign, count(*) num_sign
        FROM signups s
        INNER JOIN orders o ON s.user_id = o.user_id7
        group by o.user_id, week(s.signup_timestamp)
    ) t1 
    left join(

        select  o.user_id, week(min(o.order_timestamp)) w_first_ord
        FROMM orders o 
        group by  o.user_id
    ) on t2 ON t2.user_id = t1.user_id and t1.w_sign = t2.num_sign

答案 1 :(得分:0)

这个问题比乍看起来要困难得多,因为您将注册日期和订购日期混合在一起。为此union all有帮助。

第二,您需要列举订单。在MySQL 8+中,您可以使用窗口函数:

select year(ts) as year, week(ts) as week,
       sum(issignup) as num_signups,
       sum(order_seqnum = 1) as orders_1,
       sum(order_seqnum = 2) as orders_2,
       sum(order_seqnum = 3) as orders_3
from ((select o.order_timestamp as ts,
              row_number() over (partition by o.userid order by o.order_timestamp) as order_seqnum,
              1 as isorder, 0 as issignup
       from signups s join
            orders o 
            on s.user_id = o.user_id7
      ) union all
      (select s.signup_timestamp, null, 0 as isorder, 1 as issignup
       from signups s
      )
     ) os 
group by year(ts), week(ts)