【问题标题】:tally/count mysql results per day每天统计/计算mysql结果
【发布时间】:2011-03-29 17:12:32
【问题描述】:

假设我有一个名为“signups”的 mysql 表,其值如下:

Name            Signup Date
dog            2008-05-14 18:53:30
cat            2008-05-14 12:13:20
mouse          2008-05-14 08:51:32
giraffe        2008-05-15 22:13:31
Moose          2008-05-16 13:20:30
monkey         2008-05-16 08:51:32
mongoose       2008-05-16 22:13:31
fish           2008-05-16 13:00:30

我想生成一份关于每天有多少动物注册的报告(我不关心一天中的时间)。所以我从上面的示例表中寻找的最终结果是:

Date              Signups
2008-05-14         3
2008-05-15         1
2008-05-16         4

有没有办法在 mysql 中做到这一点,还是我需要使用另一种语言(如 PHP)来计算总数?

感谢任何想法,谢谢

【问题讨论】:

    标签: php mysql sql database


    【解决方案1】:
    SELECT  DATE(Signup_Date) AS `Date`
            , COUNT(*) AS Signups 
    FROM    `signups` 
    GROUP BY 
            DATE(Signup_Date)
    

    会给你你所追求的。

    【讨论】:

    • 谢谢,但我想知道您是否可以在这里查看同一问题的更复杂版本:stackoverflow.com/questions/5476920/…
    • 这正是我需要的,除了我需要它包括添加 0 行的天数。任何关于修改以使其工作的想法?
    【解决方案2】:
    drop table if exists users;
    create table users
    (
    user_id int unsigned not null auto_increment primary key,
    username varchar(32) unique not null,
    created_date datetime not null
    )
    engine=innodb;
    
    drop table if exists user_signup_summary;
    create table user_signup_summary
    (
    signup_date date not null primary key,
    counter int unsigned not null default 0
    )
    engine=innodb;
    
    delimiter #
    
    create trigger users_before_ins_trig before insert on users
    for each row
    begin
     insert into user_signup_summary (signup_date, counter) values (new.created_date, 1)
      on duplicate key update counter=counter+1;
    end#
    
    delimiter ;
    
    insert into users (username, created_date) values
    ('f00', now()), ('bar', now()),
    ('alpha', now() - interval 1 day), ('beta', now() - interval 1 day),
    ('gamma', now() - interval 2 day);
    
    
    select * from users;
    select * from user_signup_summary;
    

    【讨论】:

    • 嗨 f00 - 所有 3k 现有用户呢?
    • 运行一次性查询以生成统计数据
    猜你喜欢
    • 2015-04-11
    • 1970-01-01
    • 1970-01-01
    • 2016-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-20
    • 2020-08-16
    相关资源
    最近更新 更多