SQL在日期上不同并忽略时间

时间:2014-11-20 09:57:03

标签: mysql sql mysqli

我希望仅基于Dates来区分下表,同时还有平均值。有办法吗?

SELECT DISTINCT DATE_FORMAT(Date, '%Y-%m-%d'),
      AVG(value) AS Timestamp 
FROM abc GROUP BY Date

表abc

+--------------------+-------+
| Date               | value |
+--------------------+-------+
| 18-Nov-2013 12:34  |   5   |
| 19-Nov-2013 14:45  |   4   |
| 20-Nov-2013 15:11  |   3   |
| 21-Nov-2013 08:33  |   2   |
| 21-Nov-2013 11:11  |   7   |
| 21-Nov-2013 15:15  |   8   |
+--------------------+-------+

2 个答案:

答案 0 :(得分:2)

你可以这样做:

SELECT DATE_FORMAT(Dat, '%Y-%m-%d') AS dt,
       Avg(val)                     AS Timestamp
FROM   abc
GROUP  BY dt 

你可以group by使用MySQL中的别名评估列,就像我在上面的查询中所做的那样。某些DBMS(如SQL Server)不允许此类SQL,因此在这种情况下,您可以使用子查询或按功能分组:

SELECT dt,
       Avg(val)
FROM   (SELECT DATE_FORMAT(Dat, '%Y-%m-%d') AS dt,
               val
        FROM   abc) t
GROUP  BY dt 

SELECT DATE_FORMAT(Dat, '%Y-%m-%d') AS datetime,
       Avg(val)                     AS Timestamp
FROM   abc
GROUP  BY DATE_FORMAT(Dat, '%Y-%m-%d')

sqlfiddle

答案 1 :(得分:1)

您需要使用GROUP功能

SELECT DATE_FORMAT(Date, '%Y-%m-%d') AS Timestamp, AVG(value)
FROM abc
GROUP BY DATE(Date)