gpt4 book ai didi

mysql - 在sql中查找期间的计数

转载 作者:IT王子 更新时间:2023-10-29 00:33:34 26 4
gpt4 key购买 nike

我有一张 table :

 user_id | order_date 
---------+------------
12 | 2014-03-23
12 | 2014-01-24
14 | 2014-01-26
16 | 2014-01-23
15 | 2014-03-21
20 | 2013-10-23
13 | 2014-01-25
16 | 2014-03-23
13 | 2014-01-25
14 | 2014-03-22

活跃用户是指过去 12 个月登录过的用户。需要输出为

Period | count of Active user
----------------------------
Oct-2013 - 1
Jan-2014 - 5
Mar-2014 - 10

2014 年 1 月的值 - 包括 2013 年 10 月的 1 条记录和 2014 年 1 月的 4 条非重复记录)

最佳答案

您可以使用变量来计算活跃用户的运行总数:

SELECT Period,
@total:=@total+cnt AS `Count of Active Users`
FROM (
SELECT CONCAT(MONTHNAME(order_date), '-', YEAR(order_date)) AS Period,
COUNT(DISTINCT user_id) AS cnt
FROM mytable
GROUP BY Period
ORDER BY YEAR(order_date), MONTH(order_date) ) t,
(SELECT @total:=0) AS var

子查询返回每个月/年的不同 活跃用户数。外部查询使用 @total 变量来计算活跃用户计数的运行总数。

Fiddle Demo here

关于mysql - 在sql中查找期间的计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30658356/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com