如何从postgresql查询这些数据

nwlls2ji  于 2024-01-07  发布在  PostgreSQL
关注(0)|答案(1)|浏览(122)

我有这些table
| 唯一_iD|土地使用标识|日期|
| --|--|--|
| 1 | 11 |2013-04-09 2013-04-09|
| 2 | 12 |2014-03-23 2014-03-23|
| 3 | 13 |2015-09-21 2015-09-21 2015-09-21|
| 4 | 11 |2016-12-30 2016-12-30|
| 土地使用标识|土地使用名称|
| --|--|
| 11 |单个|
| 12 |雷登塞尔|
| 13 |空置|
我想使用Postgres重新创建一个表,使用连接或子查询显示按年份分类的每种房屋类型的计数,并按房屋名称分组。
就像这样。
| 名称| 2013 | 2014 | 2015 | 2016 |
| --|--|--|--|--|
| 单个| 25 | 10 | 34 | 55 |
| 住宅| 80 | 12 | 54 | 66 |
| 空置| 40 | 21 | 34 | 11 |
我该如何让这个奇迹发生?
我试过加入和子查询,但我没有得到我要找的。
这就是我所尝试的:

select a.land_use_name,
        count(b.sale_date) as "2013",
        count(c.sale_date) as "2014",
        count(d.sale_date) as "2015"
FROM land_use as a
    JOIN (SELECT land_use_id, sale_date FROM sales_details where date_part('Year', sale_date) = 2013) as b ON b.land_use_id = a.land_use_id
    JOIN (SELECT land_use_id, sale_date FROM sales_details where date_part('Year', sale_date) = 2014) as c ON c.land_use_id = b.land_use_id
    JOIN (SELECT land_use_id, sale_date from sales_details where date_part('Year', sale_date) = 2015) as d ON d.land_use_id = c.land_use_id
group BY a.land_use_name

字符串
这是我得到的结果:
| 土地使用名称| 2013 | 2014 | 2015 |
| --|--|--|--|
| 单个| 4 | 4 | 4 |
| 住宅| 26000 | 26000 | 26000 |
| 空置| 4 | 4 | 4 |

p4tfgftt

p4tfgftt1#

您可以使用条件过滤器()或扩展tablefunc

CREATE EXTENSION IF NOT EXISTS tablefunc;

SELECT *
FROM crosstab(
    $$ SELECT land_use_name, EXTRACT(YEAR FROM sale_date) AS year, COUNT(*)
       FROM sales_details
       JOIN land_use USING(land_use_id)
       GROUP BY land_use_name, year
       ORDER BY land_use_name, year $$,
    $$ SELECT DISTINCT EXTRACT(YEAR FROM sale_date) FROM sales_details ORDER BY 1 $$
) AS ct("Land Use Name" TEXT, "2013" INT, "2014" INT, "2015" INT, "2016" INT);

字符串
您必须以列的形式列出所有可能的日期,请参见"2013" INT
当使用FILTER()时:

SELECT land_use_name,
       COUNT(*) FILTER (WHERE EXTRACT(YEAR FROM sale_date) = 2013) AS "2013",
       COUNT(*) FILTER (WHERE EXTRACT(YEAR FROM sale_date) = 2014) AS "2014",
       COUNT(*) FILTER (WHERE EXTRACT(YEAR FROM sale_date) = 2015) AS "2015",
       COUNT(*) FILTER (WHERE EXTRACT(YEAR FROM sale_date) = 2016) AS "2016"
FROM sales_details
    JOIN land_use USING(land_use_id)
GROUP BY land_use_name
ORDER BY land_use_name;

相关问题