我有一个工作正常的交叉表查询。它基于客户及其总交易,按一年中的月份划分。
唯一的问题是,当一列没有数据(即一个月没有活动(时,我会得到一个 null 值,我想将其转换为零。
我已经尝试在"金额"字段上进行合并,但这不起作用。
如果有人有任何帮助,我将不胜感激。
查询为:
select *
from crosstab(
$ct$
SELECT sa.id,
company.name,
to_char(sat.transaction_date, 'YYYY-MM') AS my,
COALESCE(sat.amount,0) AS amnt
FROM sales_account_transactions sat
JOIN sales_account sa ON sa.id = sat.sales_account
JOIN company ON sa.company = company.id
WhERE sat.financial_company = 1
AND sat.transaction_date BETWEEN '2018-01-01' AND '2018-03-31'
AND sat.reversed_by = 0
AND sat.original_id = 0
GROUP BY sa.id, company.name, my, amnt
ORDER BY company.name, to_char(sat.transaction_date, 'YYYY-MM');
$ct$,
$$VALUES
('2018-01'), ('2018-02'), ('2018-03')
$$
)
as ct(id int, name text,
"Jan 2018" int, "Feb 2018" int, "Mar 2018" int);
代替select *
,使用select coalesce("Jan 2018", 0) as "Jan 2018", ...