新的与重复使用的用户,数月作为列MySQL

发布于 2025-02-13 11:34:52 字数 906 浏览 1 评论 0原文

我有一个订单表,每个订单都有一个时间戳字段以及用户_ID:

CREATE TABLE order(
id BIGINT, 
created TIMESTAMP,
user_id INT
PRIMARY KEY(id)
)

我正在尝试获得这样的东西,在其中我每月获得了新的和经常性用户的计数。用户在整个月内都是新的,他们首次购买并在此之后每次购买。

客户类型月1个月2个月3
新的计数计数计数
反复计数计数肯定

到目前为止,

SELECT 'New' AS 'Customer Type',
SUM(CASE WHEN MONTH(created) = 1 THEN 1 ELSE 0 END) month_1,
SUM(CASE WHEN MONTH(created) = 2 THEN 1 ELSE 0 END) month_2,
SUM(CASE WHEN MONTH(created) = 3 THEN 1 ELSE 0 END) month_3
FROM order
HAVING MONTH(MIN(created))

我已经计划在不在(Min(Min(创建))语句中使用联盟的连接,但我敢 有一个更好的方法

I have a order table where I have a timestamp field for each order as well as the user_id:

CREATE TABLE order(
id BIGINT, 
created TIMESTAMP,
user_id INT
PRIMARY KEY(id)
)

I'm trying to get something like this where I get the count of new and recurrent users for each month. A user is new for the whole month they made their first purchase and recurrent every purchase after that.

Customer Typemonth 1month 2month 3
newcountcountcount
recurrentcountcountcount

So far I have this:

SELECT 'New' AS 'Customer Type',
SUM(CASE WHEN MONTH(created) = 1 THEN 1 ELSE 0 END) month_1,
SUM(CASE WHEN MONTH(created) = 2 THEN 1 ELSE 0 END) month_2,
SUM(CASE WHEN MONTH(created) = 3 THEN 1 ELSE 0 END) month_3
FROM order
HAVING MONTH(MIN(created))

I was planning on using a UNION for the recurrent with a NOT IN (MIN(MONTH(created)) statement but i'm sure there's a better approach to this.

Any help will be greatly appreciated!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文