将行转换为postgresql中的列

Converting rows to columns in postgresql

我需要使用 postgresql 将行转换为列 需要resultSet如下

monthname   2017 year(amount)    2018 year(amount) 
Jan          10                    250
feb          20                    350
mar          40                    100

下面是我使用交叉表函数的查询

SELECT *
FROM   crosstab(
$$select  
SUM(standard_loan_account_balance) as TOTAL_AMOUNT
,extract (year from mgc.transaction_date) as monthname
,extract(MONTH from mgc.transaction_date) as monthnumber

from  bankfair.tbl_das_monthly_growth_chart mgc

where  mgc.transaction_date
between (select (SELECT APP.app_today_date FROM bankfair.tbl_cmn_application_date app)+'-12 month'::interval) 
and (SELECT APP.app_today_date FROM bankfair.tbl_cmn_application_date app) group by monthnumber,monthname
order by 1,2
$$
) as ct ("TOTAL_AMOUNT" numeric,"monthnumber" double precision,"monthname" double precision)

我没有得到预期的输出

我将从查询的简单非交叉表版本开始。这应该可以满足您的要求:

select to_char(mgc.transaction_date, 'Month') as monthname,
       sum(case when to_char(mgc.transaction_date, 'YYYY') = '2017'
                then standard_loan_account_balance else 0
           end) as slab_2017,
       sum(case when to_char(mgc.transaction_date, 'YYYY') = '2018'
                then standard_loan_account_balance else 0
           end) as slab_2018
from bankfair.tbl_das_monthly_growth_chart mgc
group by monthname, extract(month from mgc.transaction_date)
order by monh(mgc.transaction_date);

如果需要,您可以将其转换为交叉表版本。

在您想要的结果集中,列是

  monthname   2017 year(amount)    2018 year(amount) 

但是在限定 crosstab() 调用结果的 AS 子句中,您放置了这个,它似乎对应于您的非透视列:

   as ct ("TOTAL_AMOUNT" numeric,"monthnumber" double precision,"monthname" double precision)

这是错误的,因为 AS 子句应该准确指定旋转输出列。看来你不明白 crosstab() 的这方面,因为你把非透视输出的列。

作为交叉表的第一个参数传递的查询中的列也不匹配。第一列需要是月份的名称,第二列是年份,第三列是金额。最后,您需要将年份限制为 AS 子句中硬编码的年份。