我需要使用postgrsql将行转换为列 需要结果如下
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)
我没有得到预期的输出
答案 0 :(得分:0)
我将从一个简单的非交叉表版本的查询开始。这应该做你想要的:
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);
如果需要,您可以将其转换为交叉表版本。
答案 1 :(得分:0)
在您想要的结果集中,列是
monthname 2017 year(amount) 2018 year(amount)
但是在符合交叉调用()调用结果的AS子句中,你已经放了这个,这似乎与你的非旋转列相对应:
as ct ("TOTAL_AMOUNT" numeric,"monthnumber" double precision,"monthname" double precision)
这是错误的,因为AS子句应该精确指定pivotped-output列。您似乎没有理解crosstab()
的这一方面,因为您放置了非旋转输出的列。
作为交叉表的第一个参数传递的查询中的列也不匹配。第一列需要是月份名称,第二列是年份,第三列是金额。最后,您需要将年份限制为AS子句中硬编码的年份。