如果不是数字,有没有办法获得平均数量? 我的表:
ID| CAT | TITLE | DATE |
--|-------|---------|---------------------|
1 | CAT01 | TITLE01 | 2013-01-18 20:37:15 |
2 | CAT01 | TITLE02 | 2013-01-18 20:37:16 |
3 | CAT02 | TITLE03 | 2013-01-19 12:09:54 |
我怎么能每天获得AVG的帖子?
现在我正在使用它:
SELECT AVG(cat) / DATEDIFF('2013-01-19', '2013-01-18') as average
FROM posts
WHERE date BETWEEN '2013-01-18' AND '2013-01-19'"
但对我而言,它不会返回平均数。也许我应该首先计算(猫)AS cnt然后使用avg(cnt)AS平均值?
或AVG不能用于非数字表?
答案 0 :(得分:3)
您可以一步完成此操作。可以在此处找到经过测试的示例:http://sqlfiddle.com/#!2/05760/12
SELECT
COUNT(*) /
COUNT(DISTINCT cast(`date` as date)) avg_posts_per_day
FROM
posts
或者您可以分两步完成:
可在此处找到经过测试的示例:http://sqlfiddle.com/#!2/05760/4
SELECT
AVG(posts_per_day) AS AVG_POSTS_PER_DAY
FROM (
SELECT
CAST(`date` as date),
COUNT(*) posts_per_day
FROM posts
GROUP BY
CAST(`date` as date)
) ppd
答案 1 :(得分:0)
试试这个
SELECT COUNT(cat)/2 as avrag
FROM posts
编辑:
如果您想使用两个日期之间的平均值,请添加此
where date between 'the_date1' AND 'the_date2'
答案 2 :(得分:0)
您可以做的是获取总帖子数,自数据库中第一个时间戳以来的天数,并计算这两个数字的平均值。
答案 3 :(得分:0)
我认为您只需要用COUNT(*)
计算行数,并在datediff中添加1:
SELECT COUNT(*) / (DATEDIFF('2013-01-19', '2013-01-18')+1) as average
FROM posts
WHERE DATE(date) BETWEEN '2013-01-18' AND '2013-01-19'
这将返回平均帖子数,没有帖子的天数计算在内。
或者,根据您所追求的内容,您可能会考虑这样的事情:
SELECT
COUNT(*) /
(datediff(max(`date`), min(`date`))+1) as avg_posts
FROM
posts
答案 4 :(得分:0)
试试这个,格式化日期yyyy-MM-dd计算每天的所有帖子,然后取每天的平均值
SELECT
amount/total AS AVG_POSTS_PER_DAY, day
FROM
(
SELECT COUNT(1) amount, DATE_FORMAT(DATE, '%Y-%m-%d') day,
(SELECT COUNT(1) from posts) total
FROM posts
group by
DATE_FORMAT(DATE, '%Y-%m-%d')) a
group by day`