如果出现以下情况,如何显示按月和周的记录?

时间:2013-07-22 09:32:51

标签: php mysql sql date unix-timestamp

我在我的网站上使用PHP和MySQL。我的数据库中有一个名为users的表。它有两个字段即user_reg_date(bigint(12)) and user_last_login(bigint(12))。这两个字段以 UNIX TIMESTAMP 格式存储日期。整个表格结构如下:

user_id         varchar(32)
user_title      enum('Mr', 'Ms', 'Mrs')
user_first_name varchar(50)
user_last_name  varchar(50)
user_name   varchar(100)
user_password   varchar(50)
user_email  varchar(150)
user_dob    date    
user_hybridauth_p_name  varchar(100)
user_hybridauth_p_uid   varchar(100)
user_reg_date   bigint(12)
user_status     enum('enable', 'disable')
user_subscription   enum('lifetime', 'period')
user_update_date    bigint(12)
user_last_login     bigint(12)
user_last_activity  bigint(12)
user_created_staff_id   varchar(32)
user_updated_staff_id   varchar(32)
user_registered_type    enum('online', 'manual')

现在我想显示记录计数,即user_reg_date属于当前日期的用户数以及user_last_login属于当前日期的用户的记录数。其他查询也需要显示上周以及当前日期的最后两周的记录数。 我还希望按月显示相同的记录计数。有谁可以帮我实现这个目标?提前致谢。我试图在两个日期之间取得这样的数量,它在某种程度上完美地起作用。它给了我user_reg_date的日期明智计数,但没有给我上次登录的用户数。我只是不能写出完美的查询。我为此编写的查询如下:

    SELECT date( FROM_UNIXTIME( user_reg_date ) ) 'Current Date', COUNT( user_reg_date ) 'registered_user_count', COUNT( user_last_login ) 'logged_in_count'
FROM users
WHERE user_reg_date >=1341100800
AND user_reg_date <=1374451200
AND user_last_login >=1341100800
AND user_last_login <=1374451200
GROUP BY date( FROM_UNIXTIME( user_reg_date ) ) , date( FROM_UNIXTIME( user_last_login ) ) 

2 个答案:

答案 0 :(得分:0)

你可以做这样的事情

SELECT
  (SELECT COUNT(*) 
     FROM users
    WHERE user_last_login BETWEEN UNIX_TIMESTAMP(ADDDATE(CURDATE(), INTERVAL 1-DAYOFWEEK(CURDATE()) DAY))
                              AND UNIX_TIMESTAMP(ADDDATE(CURDATE(), INTERVAL 7-DAYOFWEEK(CURDATE()) DAY))
  ) logged_in_count,
  (SELECT COUNT(*) 
     FROM users
    WHERE user_reg_date   BETWEEN UNIX_TIMESTAMP(ADDDATE(CURDATE(), INTERVAL 1-DAYOFWEEK(CURDATE()) DAY))
                              AND UNIX_TIMESTAMP(ADDDATE(CURDATE(), INTERVAL 7-DAYOFWEEK(CURDATE()) DAY))
  ) registered_user_count

这是 SQLFiddle 演示

答案 1 :(得分:0)

SELECT columnName
  SUM(CASE WHEN REQUESTMONTH=1 THEN (REQUESTTOTAL) END) Jan,
  SUM(CASE WHEN REQUESTMONTH=2 THEN (REQUESTTOTAL) END) Feb,
  SUM(CASE WHEN REQUESTMONTH=3 THEN (REQUESTTOTAL) END) Mar,
  SUM(CASE WHEN REQUESTMONTH=4 THEN (REQUESTTOTAL) END) Apr,
  SUM(CASE WHEN REQUESTMONTH=5 THEN (REQUESTTOTAL) END) May,
  SUM(CASE WHEN REQUESTMONTH=6 THEN (REQUESTTOTAL) END) Jun,
  SUM(CASE WHEN REQUESTMONTH=7 THEN (REQUESTTOTAL) END) July,
  SUM(CASE WHEN REQUESTMONTH=8 THEN (REQUESTTOTAL) END) Aug,
  SUM(CASE WHEN REQUESTMONTH=9 THEN (REQUESTTOTAL) END) Sep,
  SUM(CASE WHEN REQUESTMONTH=10 THEN (REQUESTTOTAL) END) 'Oct',
  SUM(CASE WHEN REQUESTMONTH=11 THEN (REQUESTTOTAL) END) Nov,
  SUM(CASE WHEN REQUESTMONTH=12 THEN (REQUESTTOTAL) END) 'Dec'
FROM tableName