我正在创建一个sql报表 answers
表格:
id | created_at
1 | 2018-03-02 18:05:56
2 | 2018-04-02 18:05:56
3 | 2018-04-02 18:05:56
4 | 2018-05-02 18:05:56
5 | 2018-06-02 18:05:56
输出为:
weeks_ago | record_count (# of rows per weekly cohort) | growth (%)
-4 | 21 | 22%
-3 | 22 | -12%
-2 | 32 | 2%
-1 | 2 | 20%
0 | 31 | 0%
我的查询当前出错:
1111 - Invalid use of group function
我做错什么了?
SELECT floor(datediff(f.created_at, curdate()) / 7) AS weeks_ago,
count(DISTINCT f.id) AS "New Records in Cohort",
100 * (count(*) - lag(count(*), 1) over (order by f.created_at)) / lag(count(*), 1) over (order by f.created_at) || '%' as growth
FROM answers f
WHERE f.completed_at IS NOT NULL
GROUP BY weeks_ago
HAVING count(*) > 1;
2条答案
按热度按时间p1iqtdky1#
你不能使用
lag
包含COUNT
aggregate函数,因为使用aggregate function contain aggregate函数时它无效。您可以尝试使用子查询来创建它。
wr98u20j2#
我想您需要查找除当前行以外的所有行的运行计数。我想你可以把这个
LAG
功能如下:你可以随心所欲地除法和乘法。
不。你只需要分开
GROUP BY
以及LAG OVER
:小提琴