按其他(日期)列分组的一列复杂的 PostgreSQL 平均值

PostgreSQL average of one column complex grouped by other (date) column

这是我的数据库的简化版本table。

id firstregistration km
1 2017-03-24 234
2 2019-10-08 3456
3 2020-02-07 2454
4 2019-11-28 7686
5 2019-01-18 4564

table 包含汽车数据,例如:首次注册日期、里程、价格、车型...

我的目标是构造查询以从此数据库获取分析指标 table。我的最终目标应该是这样的:

我需要使用首次注册日期来构建年龄组,并根据该年龄组提取其他数据。

目前我已经解决了第一列和第二列。 SQL 查询如下所示:

SELECT SUM(CASE WHEN date_part('year', age(firstregistration))<1 THEN 1 ELSE 0 END) AS "0-1",
    SUM(CASE WHEN date_part('year', age(firstregistration)) BETWEEN 1 AND 2 THEN 1 ELSE 0 END) AS "1-2",
    SUM(CASE WHEN date_part('year', age(firstregistration)) BETWEEN 2 AND 3 THEN 1 ELSE 0 END) AS "2-3",
    SUM(CASE WHEN date_part('year', age(firstregistration)) BETWEEN 3 AND 4 THEN 1 ELSE 0 END) AS "3-4",
    SUM(CASE WHEN date_part('year', age(firstregistration)) BETWEEN 4 AND 5 THEN 1 ELSE 0 END) AS "4-5",
    SUM(CASE WHEN date_part('year', age(firstregistration)) BETWEEN 5 AND 6 THEN 1 ELSE 0 END) AS "5-6",
    SUM(CASE WHEN date_part('year', age(firstregistration)) BETWEEN 6 AND 7 THEN 1 ELSE 0 END) AS "6-7",
    SUM(CASE WHEN date_part('year', age(firstregistration)) BETWEEN 7 AND 8 THEN 1 ELSE 0 END) AS "7-8",
    SUM(CASE WHEN date_part('year', age(firstregistration)) BETWEEN 8 AND 9 THEN 1 ELSE 0 END) AS "8-9",
    SUM(CASE WHEN date_part('year', age(firstregistration)) BETWEEN 8 AND 9 THEN 1 ELSE 0 END) AS "9-10",
    SUM(CASE WHEN date_part('year', age(firstregistration)) >= 10 THEN 1 ELSE 0 END) AS ">=10" FROM car_table

为此,我得到如下所示的输出:

这个结果非常好,它解决了第一张图片上图表的前两列。现在我无法添加这些组的平均公里数据。

有谁知道如何轻松实现它? 需要补充的重要一点是,平均 KM 查询不需要成为我的第一个查询的一部分。使它成为一个额外的查询就足够了。谢谢

我想你可以一次查询得到结果。


SELECT  age , COUNT(age) as NroCars , AVG(km) , AVG(price) FROM (
     SELECT  date_part('year', age(firstregistration)) as age,
             km ,
             price
     FROM TABLE 
) temp_table
GROUP BY age