MySql选择并计算每天的数据数量

时间:2014-01-02 07:45:25

标签: mysql sql

我有一个包含列的下表:

id    |    data    |    date

如何查询1到30天的日期范围内的所有数据并计算每天的所有数据?

我尝试了一些东西,但它也按秒分组

Select count(data) as data 
From table
Where date between '2013-12-02 00-00-00' and '2014-01-02 23:59:59'
group by date

我想实现

day 1  |  day 2  |  day  | day 4  | . . .
 3     |   4     |   2   |    5   | . . .

3 个答案:

答案 0 :(得分:1)

尝试以下

SELECT DATE_FORMAT(date, '%Y-%m-%d') AS the_date
     , COUNT(*) AS count 
  FROM table 
 WHERE date BETWEEN DATE_FORMAT('2014-11-28', '%Y-%m-%d') AND DATE_FORMAT('2014-12-05', '%Y-%m-%d') 
 GROUP 
    BY the_date

答案 1 :(得分:0)

SELECT @count:=0;
SELECT CONCAT('day ',@count+1) as day, COUNT(*), date 
FROM date between
  '2013-12-02 00-00-00'
AND
  '2014-01-02 23:59:59')
GROUP BY date

答案 2 :(得分:0)

好像你想要一个如下所示的查询:

SELECT 
CASE date_format(date ,"%W")
WHEN 'Monday' THEN IFNULL((SELECT COUNT(id) FROM YOUR_TABLE WHERE 
date_format(date ,"%W") ='Monday' ) ,0) ELSE 0
END AS 'Monday',
CASE date_format(date ,"%W")
WHEN 'Tuesday' THEN IFNULL((SELECT COUNT(id) FROM YOUR_TABLE WHERE 
date_format(date ,"%W") ='Tuesday' ) ,0) ELSE 0
END AS 'Tuesday',
CASE date_format(date ,"%W")
WHEN 'Wednesday' THEN IFNULL((SELECT COUNT(id) FROM YOUR_TABLE WHERE 
date_format(date ,"%W") ='Wednesday' ) ,0) ELSE 0
END AS 'Wednesday',
CASE date_format(date ,"%W")
WHEN 'Thursday' THEN IFNULL((SELECT COUNT(id) FROM YOUR_TABLE WHERE 
date_format(date ,"%W") ='Thursday' ) ,0) ELSE 0
END AS 'Thursday',
CASE date_format(date ,"%W")
WHEN 'Friday' THEN IFNULL((SELECT COUNT(id) FROM YOUR_TABLE WHERE 
date_format(date ,"%W") ='Friday' ) ,0) ELSE 0
END AS 'Friday',
CASE date_format(date ,"%W")
WHEN 'Saturday' THEN IFNULL((SELECT COUNT(id) FROM YOUR_TABLE WHERE 
date_format(date ,"%W") ='Saturday' ) ,0) ELSE 0
END AS 'Saturday',
CASE date_format(date ,"%W")
WHEN 'Sunday' THEN IFNULL((SELECT COUNT(id) FROM YOUR_TABLE WHERE 
date_format(date ,"%W") ='Sunday' ) ,0) ELSE 0
END AS 'Sunday'
FROM YOUR_TABLE