我有以下查詢來獲取每月累計用戶數:獲取累積月度用戶根據用戶的電子郵件數
SELECT RTRIM(TO_CHAR(DATE_TRUNC('month', created_at), 'Month YYYY')) AS month,
SUM(COUNT(id)::int) OVER (ORDER BY DATE_TRUNC('month', created_at)) AS total,
SUM((email like '%@domain%')::int) AS with_domain,
SUM((email not like '%@domain%')::int) AS without_domain
FROM users
GROUP BY DATE_TRUNC('month', created_at)
ORDER BY DATE_TRUNC('month', created_at);
結果如下:
[
{"month"=>"October 2015", "total"=>2, "with_domain"=>1, "without_domain"=>1},
{"month"=>"December 2015", "total"=>6, "with_domain"=>4, "without_domain"=>0},
{"month"=>"January 2016", "total"=>13, "with_domain"=>4, "without_domain"=>3},
{"month"=>"February 2016", "total"=>15, "with_domain"=>2, "without_domain"=>0},
{"month"=>"March 2016", "total"=>36, "with_domain"=>15, "without_domain"=>6},
]
見,total
怎麼算的累積和其他人不?
我嘗試以下查詢:
SELECT RTRIM(TO_CHAR(DATE_TRUNC('month', created_at), 'Month YYYY')) AS month,
SUM(COUNT(id)::int) OVER (ORDER BY DATE_TRUNC('month', created_at)) AS total,
SUM((email like '%@domain%')::int) OVER (ORDER BY DATE_TRUNC('month', created_at)) AS with_domain,
SUM((email not like '%@domain%')::int) OVER (ORDER BY DATE_TRUNC('month', created_at)) AS without_domain
FROM users
GROUP BY DATE_TRUNC('month', created_at)
ORDER BY DATE_TRUNC('month', created_at);
但它拋出
column "users.email" must appear in the GROUP BY clause or be used in an aggregate function LINE 3: SUM((email like '%@domain%')::int) OVER (ORDER BY...^: SELECT RTRI
並添加email
到GROUP BY
條款是毫無意義可言......
如何使所有累計計數(就像total
一樣)?
預期的結果是一樣
[
{"month"=>"October 2015", "total"=>2, "with_domain"=>1, "without_domain"=>1},
{"month"=>"December 2015", "total"=>6, "with_domain"=>5, "without_domain"=>1},
{"month"=>"January 2016", "total"=>13, "with_domain"=>9, "without_domain"=>4},
{"month"=>"February 2016", "total"=>15, "with_domain"=>11, "without_domain"=>4},
{"month"=>"March 2016", "total"=>36, "with_domain"=>26, "without_domain"=>10},
]
你的錯誤是,你正試圖獲得'運行總量(電子郵件[不] LIKE「%@域% '):: int'而不是'SUM(email [not] like'%@ domain%'):: int)'。 –