计算每天的访问量

准备数据:

  1. CREATE TABLE t1 (year YEAR(4), month INT(2) UNSIGNED ZEROFILL,
  2. day INT(2) UNSIGNED ZEROFILL);
  3. INSERT INTO t1 VALUES(2000,1,1),(2000,1,20),(2000,1,30),(2000,2,2),
  4. (2000,2,23),(2000,2,23);

表格中的数据是用户访问网站的年,月,日,现在要计算每个月访问的天数,可以用以下语句:

  1. SELECT year,month,BIT_COUNT(BIT_OR(1<<day)) AS days FROM t1
  2. GROUP BY year,month;

结果是,1月份有3天,2月份有2天,如下表所示:

  1. +------+-------+------+
  2. | year | month | days |
  3. +------+-------+------+
  4. | 2000 | 01 | 3 |
  5. | 2000 | 02 | 2 |
  6. +------+-------+------+

其中,相同的天(23日)只算一次。

原文: https://strongyoung.gitbooks.io/mysql-reference-manual/content/tutorial/common_queries/calculating_visits_per_day.html