Unnest 可以在 PostgreSQL 中过滤吗?
Can Unnest filtered in PostgreSQL?
我有一个 table 的值,其中“TAHUN”列按 date_part('year'::text, insert_date) 分组,值为 1000在“TAHUN”列中总计
我想像这样将行转置为列(但“TAHUN”列保持动态,因此我不必在年终时手动插入它):
我对使用 unnest 按列“TAHUN”进行过滤感到困惑。这是我的查询:
SELECT
unnest(array['PENDAPATAN', 'PENJUALAN 1', 'PENJUALAN 2', 'PENDAPATAN LAIN-LAIN', 'TOTAL PENDAPATAN', 'HARGA POKOK PENJUALAN (HPP)', 'PEMBELIAN', 'ONGKOS KIRIM']) AS "title",
unnest(array["PENDAPATAN", "PENJUALAN 1", "PENJUALAN 2", "PENDAPATAN LAIN-LAIN", "TOTAL PENDAPATAN", "HARGA POKOK PENJUALAN (HPP)", "PEMBELIAN", "ONGKOS KIRIM"]) FILTER (WHERE "TAHUN" != 1000) AS "dynamic year",
unnest(array["PENDAPATAN", "PENJUALAN 1", "PENJUALAN 2", "PENDAPATAN LAIN-LAIN", "TOTAL PENDAPATAN", "HARGA POKOK PENJUALAN (HPP)", "PEMBELIAN", "ONGKOS KIRIM"]) FILTER (WHERE "TAHUN" = 1000) AS "total"
FROM vw_blm_dashboard_hasil_usaha
GROUP BY "title", "dynamic year", "total";
unnest可以过滤吗?或者您还有其他方法可以解决这个问题吗?
先致谢
您需要将取消嵌套移动到 FROM 子句中,以便获得可以引用的列。
我个人认为使用 VALUES 子句编写此代码更容易阅读:
SELECT
x.title ,
max(x.value) FILTER (WHERE v."TAHUN" = 2019) AS "2019",
max(x.value) FILTER (WHERE v."TAHUN" = 2020) AS "2020",
max(x.value) FILTER (WHERE v."TAHUN" = 2021) AS "2021",
max(x.value) FILTER (WHERE v."TAHUN" = 1000) AS "total"
FROM vw_blm_dashboard_hasil_usaha v
CROSS JOIN LATERAL (
values ("PENDAPATAN", 'PENDAPATAN'),
("PENJUALAN 1", 'PENJUALAN 1'),
("PENJUALAN 2", 'PENJUALAN 2'),
... all other columns come here ...
) as x(value, title)
GROUP BY x.title;
我有一个 table 的值,其中“TAHUN”列按 date_part('year'::text, insert_date) 分组,值为 1000在“TAHUN”列中总计
我想像这样将行转置为列(但“TAHUN”列保持动态,因此我不必在年终时手动插入它):
我对使用 unnest 按列“TAHUN”进行过滤感到困惑。这是我的查询:
SELECT
unnest(array['PENDAPATAN', 'PENJUALAN 1', 'PENJUALAN 2', 'PENDAPATAN LAIN-LAIN', 'TOTAL PENDAPATAN', 'HARGA POKOK PENJUALAN (HPP)', 'PEMBELIAN', 'ONGKOS KIRIM']) AS "title",
unnest(array["PENDAPATAN", "PENJUALAN 1", "PENJUALAN 2", "PENDAPATAN LAIN-LAIN", "TOTAL PENDAPATAN", "HARGA POKOK PENJUALAN (HPP)", "PEMBELIAN", "ONGKOS KIRIM"]) FILTER (WHERE "TAHUN" != 1000) AS "dynamic year",
unnest(array["PENDAPATAN", "PENJUALAN 1", "PENJUALAN 2", "PENDAPATAN LAIN-LAIN", "TOTAL PENDAPATAN", "HARGA POKOK PENJUALAN (HPP)", "PEMBELIAN", "ONGKOS KIRIM"]) FILTER (WHERE "TAHUN" = 1000) AS "total"
FROM vw_blm_dashboard_hasil_usaha
GROUP BY "title", "dynamic year", "total";
unnest可以过滤吗?或者您还有其他方法可以解决这个问题吗?
先致谢
您需要将取消嵌套移动到 FROM 子句中,以便获得可以引用的列。
我个人认为使用 VALUES 子句编写此代码更容易阅读:
SELECT
x.title ,
max(x.value) FILTER (WHERE v."TAHUN" = 2019) AS "2019",
max(x.value) FILTER (WHERE v."TAHUN" = 2020) AS "2020",
max(x.value) FILTER (WHERE v."TAHUN" = 2021) AS "2021",
max(x.value) FILTER (WHERE v."TAHUN" = 1000) AS "total"
FROM vw_blm_dashboard_hasil_usaha v
CROSS JOIN LATERAL (
values ("PENDAPATAN", 'PENDAPATAN'),
("PENJUALAN 1", 'PENJUALAN 1'),
("PENJUALAN 2", 'PENJUALAN 2'),
... all other columns come here ...
) as x(value, title)
GROUP BY x.title;