MySQL获取所有日子的网站统计信息

时间:2014-01-21 23:16:20

标签: php mysql vb.net datetime statistics

每次有新访问者访问我的网站时,他们都会登录到数据库。我可以使用此查询选择过去七天内特定日期的用户数:

SELECT COUNT(*) AS Hits, DATE_FORMAT(Date, '%Y-%m-%d') AS HitDay FROM(stats) WHERE Date >= DATE_SUB(SYSDATE(), INTERVAL 7 DAY) GROUP BY DATE(Date) ORDER BY Date ASC   

问题在于我必须在VB中的图表中将此数据绘制为项目的一部分,如果在特定日期没有点击,那么图表上的两个日期之间就存在差距。我想知道如果没有任何访问者,是否可以在Hits列中返回过去七个日期内的所有日期,并且返回0。间隔也可以改变,因此它可以在1到31之间。

也许这可以通过程序或功能来完成?任何想法都会很棒,但我试图不填补VB中的空白。

1 个答案:

答案 0 :(得分:1)

您可以生成7天,并使用下面的统计信息LEFT JOIN

SELECT COUNT(stats.date) AS Hits, DATE_FORMAT(days.Date, '%Y-%m-%d') AS HitDay 
FROM
   (SELECT CURDATE() as date
    UNION SELECT CURDATE() - INTERVAL 1 DAY
    UNION SELECT CURDATE() - INTERVAL 2 DAY
    UNION SELECT CURDATE() - INTERVAL 3 DAY
    UNION SELECT CURDATE() - INTERVAL 4 DAY
    UNION SELECT CURDATE() - INTERVAL 5 DAY
    UNION SELECT CURDATE() - INTERVAL 6 DAY
    )days
LEFT JOIN stats ON days.date = stats.date
GROUP BY DATE(days.Date) ORDER BY days.Date ASC

sqlFiddle

如果您的间隔更改可能指定更多如下(最多128天),只需将条件< 7更改为您的间隔

SELECT COUNT(stats.date) AS Hits, DATE_FORMAT(days.Date, '%Y-%m-%d') AS HitDay 
FROM
   (SELECT CURDATE() - INTERVAL 
     (d1.value+d2.value+d3.value+d4.value+
      d5.value+d6.value+d7.value) day as date
    FROM (SELECT 0 as value UNION SELECT 1)d1,
         (SELECT 0 as value UNION SELECT 2)d2,
         (SELECT 0 as value UNION SELECT 4)d3,
         (SELECT 0 as value UNION SELECT 8)d4,
         (SELECT 0 as value UNION SELECT 16)d5,
         (SELECT 0 as value UNION SELECT 32)d6,
         (SELECT 0 as value UNION SELECT 64)d7
    WHERE (d1.value+d2.value+d3.value+d4.value+
      d5.value+d6.value+d7.value) < 7
    )days
LEFT JOIN stats ON days.date = DATE(stats.date)
GROUP BY DATE(days.Date) ORDER BY days.Date ASC

sqlFiddle