我在a中有一个表格,其结构如下:
CustID --- DateAdded ---
396 2012-02-09
396 2012-02-09
396 2012-02-08
396 2012-02-07
396 2012-02-07
396 2012-02-07
396 2012-02-06
396 2012-02-06
我想知道如何计算SQL中过去7天每天的记录数,然后将其作为整数返回。
目前我编写了以下SQL查询:
SELECT *
FROM Responses
WHERE DateAdded >= dateadd(day, datediff(day, 0, GetDate()) - 7, 0)
RETURN
但是,这仅返回过去7天的所有条目。如何计算过去7天内每天的记录?
答案 0 :(得分:24)
select DateAdded, count(CustID)
from Responses
WHERE DateAdded >=dateadd(day,datediff(day,0,GetDate())- 7,0)
GROUP BY DateAdded
答案 1 :(得分:6)
select DateAdded, count(CustID)
from tbl
group by DateAdded
大约7天的时间间隔是依赖于DB的问题
答案 2 :(得分:2)
SELECT DateAdded, COUNT(1) AS NUMBERADDBYDAY
FROM Responses
WHERE DateAdded >= dateadd(day,datediff(day,0,GetDate())- 7,0)
GROUP BY DateAdded
答案 3 :(得分:2)
这类似于上面的答案,它使用MySql DATE_FORMAT()函数。我还选择了1月的一个特定星期。
SELECT
DatePart(day, DateAdded) AS date,
COUNT(entryhash) AS count
FROM Responses
where DateAdded > '2020-01-25' and DateAdded < '2020-02-01'
GROUP BY
DatePart(day, DateAdded )
答案 4 :(得分:0)
SELECT count(*), dateadded FROM Responses
WHERE DateAdded >=dateadd(day,datediff(day,0,GetDate())- 7,0)
group by dateadded
RETURN
这将为您提供每个日期添加值的记录计数。不要错误地在select中添加更多列,期望每天只获得一个计数。 group by子句将为列出的每个列的唯一实例提供一行。
答案 5 :(得分:0)
select DateAdded, count(DateAdded) as num_records
from your_table
WHERE DateAdded >=dateadd(day,datediff(day,0,GetDate())- 7,0)
group by DateAdded
order by DateAdded
答案 6 :(得分:0)
你也可以试试这个:
SELECT DISTINCT(DATE(dateadded))AS unique_date,COUNT(*)AS amount 从表 GROUP BY unique_date ORDER BY unique_date ASC
答案 7 :(得分:0)
如果您的时间戳记包含时间,而不仅包括日期,请使用:
SELECT DATE_FORMAT('timestamp', '%Y-%m-%d') AS date, COUNT(id) AS count FROM table GROUP BY DATE_FORMAT('timestamp', '%Y-%m-%d')