Mysql查询提取日期+按天分组

时间:2013-06-01 09:22:24

标签: mysql sql

简单问题:为什么以下查询不输出perday

SELECT FROM_UNIXTIME(`date`,"%Y-%m-%d") AS `perday`, COUNT(*) AS `count` 
FROM `data` 
WHERE `group` = 1
GROUP BY `perday`

计数输出正确,但perday保持为空。 data表格如下:

 |   id   |   group   |          date          |
------------------------------------------------
 |   1    |     1     |  2013-04-13 06:01:02   |
 |   2    |     1     |  2013-04-13 14:24:18   |
 |   3    |     2     |  2012-01-21 21:33:03   |
              Ect.

谢谢!

编辑:

预期产出:

 |   perday   |
 --------------
 | 2013-04-13 |
 | 2012-01-21 |

3 个答案:

答案 0 :(得分:5)

删除WHERE子句,

SELECT  FROM_UNIXTIME(date,'%Y-%m-%d') AS perday, 
        SUM(`group` = 1)  AS `count` 
FROM    data 
GROUP   BY FROM_UNIXTIME(date,'%Y-%m-%d')

如果日期格式为2013-04-13 06:01:02,那么为什么要使用FROM_UNIXTIME?不是DATE_FORMAT而是吗?

SELECT  DATE_FORMAT(date, '%Y-%m-%d') AS perday, 
        SUM(`group` = 1)  AS `count` 
FROM    data 
GROUP   BY DATE(date)
ORDER   BY date

这将显示表格中的所有可用日期。

但是,如果您只想要选定的group

SELECT  DATE_FORMAT(date, '%Y-%m-%d') AS perday, 
        COUNT(*)  AS `count` 
FROM    data 
WHERE   `group` = 1
GROUP   BY DATE(date)
ORDER   BY date

答案 1 :(得分:0)

你可能正在寻找这个

    SELECT DATE_FORMAT(`date`,"%Y-%m-%d") AS `perday`, COUNT(*) AS `count` 
    FROM `data` 
    WHERE `group` = 1
    GROUP BY `perday`

DEMO HERE

答案 2 :(得分:0)

MySQL DATE()DATETIME表达式中取出DATE部分。正如您的Expected output此查询没问题。

SELECT
  DATE(`date`) AS `perday`,
  COUNT(*) AS `count`
FROM `data`
GROUP BY `perday`