我刚刚开始学习 SQLite,有一个问题。
这是我的意思的一个例子。
这是我的 CSV:
date
2010-10-24
2010-10-31
2010-11-01
2011-02-14
2011-02-15
2011-02-16
2011-10-01
2012-01-15
2012-05-12
2012-05-14
2012-08-12
2012-08-26
我的代码:
SELECT STRFTIME('%Y-%m', date) AS 'month', COUNT() AS 'month_count'
FROM tableName
GROUP BY STRFTIME('%Y-%m', date);
结果(以逗号分隔的形式):
month, month_count
2010-10, 2
2010-11, 1
2011-02, 3
2011-10, 1
2012-01, 1
2012-05, 2
2012-08, 2
我现在正在寻找的是一种获取每月“month_count”平均数的方法,这当然与“month_count”的平均值不同。也就是说,前者等于0.55,而后者等于1.71,我正在尝试计算前者。
我尝试使用 AVG(COUNT()),尽管这显然没有逻辑意义。
我猜我必须将代码生成的表存储为临时文件,然后从中获取平均值,尽管我不确定如何正确编写它。
有人知道我错过了什么吗?
最佳答案
尝试下面的代码:
create table test(date date);
insert into test values ('2010-10-24');
insert into test values ('2010-10-31');
insert into test values ('2010-11-01');
insert into test values ('2011-02-14');
insert into test values ('2011-02-15');
insert into test values ('2011-02-16');
insert into test values ('2011-10-01');
insert into test values ('2012-01-15');
insert into test values ('2012-05-12');
insert into test values ('2012-05-14');
insert into test values ('2012-08-12');
insert into test values ('2012-08-26');
SELECT a.tot_months
, b.month_diff
, cast(a.tot_months as float) / b.month_diff avg_count
FROM (SELECT COUNT(*) tot_months FROM test) a
, (SELECT cast((strftime('%m',max(date))+12*strftime('%Y',max(date))) as int) -
cast((strftime('%m',min(date))+12*strftime('%Y',min(date))) as int) as 'month_diff'
FROM test) b
;
输出:
C:\scripts>sqlite3 < foo.sql
12|22|0.545454545454545
关于SQLite:如何找到行数的每日/每周/每月/每年平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11143264/