【问题标题】:Get users that made order every month from MySQL获取每月从 MySQL 下订单的用户
【发布时间】:2021-03-20 00:09:39
【问题描述】:

这是我的数据库表:orders

id user_id order_id datetime
1 1 1245652 1607444387
2 2 3265784 1607357987
3 1 9521014 1607357927
4 3 1036951 1607317987

我想要一份每月至少下一次订单的用户列表。我该怎么做?

【问题讨论】:

  • 为什么用jquery标记?
  • 我们说现在是八月?那么您想要今年 1 月到 8 月的数据吗?
  • @WillardSolutions 错误,我想标记查询。固定的。谢谢
  • 每个月的什么时间段?
  • @wpanchev 我想获取订单之间的时间差异小于 30 天的用户列表

标签: mysql sql datetime aggregate-functions


【解决方案1】:

你可以这样做:

select user_id
from orders o
where datetime >= :from and datetime < :to
group by user_id
having count(distinct extract(year_month from from_unixtime(datetime))) = :num_months

:from:to:num_months表示参数。前两个定义您想要的日期范围。第三个表示在时间范围内构成“每个月”的月数。

【讨论】:

  • 谢谢,我认为查询中存在一些问题,当我运行查询时,我得到语法错误我更正查询:select user_id from orders t where datetime >= :from and datetime
【解决方案2】:

您可以将每个用户的月数与表中的总月数进行比较,如下所示:

select user_id
from mytable t
group by user_id
having count(distinct date_format(from_unixtime(datetime), '%Y-%m-01')) 
    = (select timestampdiff(month, min(datetime), max(datetime)) from mytable)

【讨论】:

    【解决方案3】:

    您可以使用解析函数count如下:

    Select distinct user_id from
    (Select user_id,
           Count(distinct extract(year_month from_unixtime(datetime))
                 over () as total_months,
           Count(distinct extract(year_month from_unixtime(datetime)) 
                 over (partition by user_id) as user_all_months
      From your_table) t
    Where user_all_months = total_months;
    

    【讨论】:

      猜你喜欢
      • 2021-01-27
      • 1970-01-01
      • 1970-01-01
      • 2015-03-24
      • 1970-01-01
      • 1970-01-01
      • 2011-05-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多