SQL dateadd和datediff

时间:2017-03-07 07:32:28

标签: mysql sql

我试图写一个SQL语句,它会返回每天的记录数。

这是我的表

id |      ip       |       date
----------------------------------------
1   136.196.41.91   2017-01-01 11:08:14
2   28.158.146.198  2017-01-01 11:08:15
3   209.140.42.236  2017-01-01 11:08:16
4   241.184.227.171 2017-01-02 11:08:17
5   6.183.99.169    2017-01-02 11:08:18
6   105.18.254.15   2017-01-03 11:08:19

预期结果类似于:

2017-01-01: 3
2017-01-02: 2
2017-01-03: 1

我正在尝试这个

select date, count(id)
from demo
WHERE date >=dateadd(day,datediff(day,0,GetDate())-7,0)
GROUP BY date

但由于某种原因,我在" phpmyadmin"

中收到此错误
Error

SQL query: Documentation

select date, count(id)
from demo
WHERE date >=dateadd(day,datediff(day,0,GetDate())-7,0)
GROUP BY date LIMIT 0, 25

MySQL said: Documentation
#1582 - Incorrect parameter count in the call to native function 'datediff'

我无法找到我做错的事。

我认为它可能来自日期格式,因此我将其更改为日期但没有运气。

请告知。

4 个答案:

答案 0 :(得分:2)

试试这个

SELECT DATE(`date`), count(*) FROM demo
GROUP BY DATE(`date`)
-- here your ordering criteria
LIMIT 0, 25

答案 1 :(得分:1)

MySQL中,DATEDIFF函数只接受2个参数:

DATEDIFF(date1, date2)

将返回date1和date 2之间的差异,如date1-date2

See w3schools.com/sql/func_datediff_mysql.asp

答案 2 :(得分:1)

检查是否有这个帮助,

select date(date), count(*) from demo group by date(date);

答案 3 :(得分:0)

Use GROUP BY Clause only :

SELECT date, count(id)
FROM demo
GROUP BY date

you need WHERE condition means : 

SELECT date, count(id)
FROM demo
WHERE DATEDIFF(your_datecolumn,GETDATE()) <= 0
GROUP BY date