我有一张桌子上面有这样的记录:
CREATE TABLE sample (
ix int unsigned auto_increment primary key,
start_active datetime,
last_active datetime
);
我需要知道在过去的30天里有多少记录是活跃的。天数也应该递增排序,以便从最早的天数返回到最新的天数。
我正在使用MySQL,查询将从PHP运行,但我并不真正需要PHP代码,只需要查询。
这是我的开始:
SELECT COUNT(1) cnt, DATE(?each of last 30 days?) adate
FROM sample
WHERE adate BETWEEN start_active AND last_active
GROUP BY adate;
最佳答案
做一个外部连接。
没有桌子?做一张桌子。为了这个我总是摆一张假桌子。
create table artificial_range(
id int not null primary key auto_increment,
name varchar( 20 ) null ) ;
-- or whatever your database requires for an auto increment column
insert into artificial_range( name ) values ( null )
-- create one row.
insert into artificial_range( name ) select name from artificial_range;
-- you now have two rows
insert into artificial_range( name ) select name from artificial_range;
-- you now have four rows
insert into artificial_range( name ) select name from artificial_range;
-- you now have eight rows
--etc.
insert into artificial_range( name ) select name from artificial_range;
-- you now have 1024 rows, with ids 1-1024
现在方便使用,并将其限制为30天,以便:
编辑:JR劳霍恩注释:
您需要将“date_add”更改为“date_sub”,以在创建的视图中获取前30天。
谢谢JR!
create view each_of_the_last_30_days as
select date_sub( now(), interval (id - 1) day ) as adate
from artificial_range where id < 32;
现在在您的查询中使用这个(我还没有实际测试您的查询,我只是假设它工作正常):
编辑:我应该以另一种方式加入:
SELECT COUNT(*) cnt, b.adate
FROM each_of_the_last_30_days b
left outer join sample a
on ( b.adate BETWEEN a.start_active AND a.last_active)
GROUP BY b.adate;
关于sql - SQL查询与日期范围内的日期匹配的记录数?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/1280753/