我需要计算用于计算每月唯一身份用户的唯一用户ID的总和,这需要每天进行。那是今天它必须显示从今天起30天前的总和,并且对于昨天,它需要计算从前30天开始的总和。
和今天一样,它应该从2013年4月27日开始计算,而昨天则是从2013年4月26日开始计算。表格结构如下:date uid visits
27-04-2013 11 45
27-04-2013 11 45
26-04-2013 11 45
25-04-2013 11 45
24-04-2013 11 45
这类似于运行总计,但仅限30天。
我使用了 DATE_ADD(date,INTERVAL -30 day)
SELECT DISTINCT date,COUNT(uid) FROM tablename
WHERE DATE_ADD(date,INTERVAL -30 day) AND date GROUP BY date
但为此,与此查询相比,我得到的结果不同。
SELECT COUNT( `uID` )
FROM tablename
WHERE date
BETWEEN '2013-04-27'
AND '2013-05-27'
这仅适用于COUNT。我需要计算计数的总和。
答案 0 :(得分:4)
请不要在列名中使用MySQL保留关键字。因此,我在查询中将date
更改为myDate
。
我相信你看到的第一步如下。
select myDate, sum(visits) as 'Total Visits' from tablename GROUP BY myDate;
对于上个月的数据,请使用以下查询。
select myDate, sum(visits) as 'Total Visits' from tablename
GROUP BY myDate
HAVING myDate BETWEEN '2013-04-27' AND '2013-05-27';
我希望这就是你所期待的。
select myDate, uid, COUNT(visits) as 'Total Visits' from tablename
GROUP BY myDate
HAVING myDate BETWEEN '2013-04-27' AND '2013-05-27';
select * from tablename
GROUP BY uid
HAVING
COUNT(DISTINCT myDate)>=30
AND
myDate BETWEEN '2013-04-27' AND '2013-05-27';
出于演示的目的,我在下面的演示链接中使用了3天的数据。
注意:更改将在以下行
COUNT(DISTINCT myDate)>=3
^^ --> This would be number of days in month (as I am using 3 days only, I have 3)
&安培;
myDate BETWEEN '2013-04-27' AND '2013-04-29';
^^^^^^^^^^^ ^^^^^^^^^^^^
我认为对于myDate BETWEEN '2013-04-27' AND '2013-04-29';
,您应该根据Mifeet的回答使用date BETWEEN DATE_ADD(date, INTERVAL -30 day) AND CURDATE()
。
答案 1 :(得分:0)
我无法从这个问题中看出你是想在一天或过去的所有日子里得到这个。如果是后者,这是一种方法:
SELECT DATE_ADD(date,INTERVAL n.n day) as thedate,
COUNT(distinct uid) as numUsers, sum(visits) as totVisits
FROM tablename t cross join
(select 0 as n union all select 1 union all select 2 union all
select 3 union all select 4 union all select 5 union all
. . .
select 27 union all select 28 union all select 29
) n
group by DATE_ADD(date,INTERVAL n.n day) ;
您的第一个查询:
SELECT DISTINCT date,COUNT(uid)
FROM tablename
WHERE DATE_ADD(date,INTERVAL -30 day) AND date
GROUP BY date
有两个缺点。首先,where
子句不是布尔值。我认为你的意思是:
where date between DATE_ADD(now(),INTERVAL -30 day) AND now()
此外,使用distinct
时,您不需要group by
(也不应该有!)。
编辑:
所以,在你的小提琴中运行它,看它返回数据中每天的数字(有6天的历史而不是30天):
SELECT DATE_ADD(mydate, INTERVAL n.n day) as thedate,
COUNT(distinct uid) as numUsers, sum(visits) as totVisits
FROM tablename t cross join
(select 0 as n union all select 1 union all select 2 union all
select 3 union all select 4 union all select 5
) n
where DATE_ADD(mydate, INTERVAL n.n day) < now()
group by DATE_ADD(mydate, INTERVAL n.n day) ;
您会注意到它会跳过没有用户的日期。