G. *_*tho 1 postgresql postgresql-9.1
我有一个包含以下列的表:
现在我将执行这个查询:
select sum(debit - credit), payment_method, class
from my_table
group by payment_method, class
Run Code Online (Sandbox Code Playgroud)
而且由于我有各种付款方式和各种类,因此我将有几行结果集。
现在,我希望能够汇总此结果并仅按类对输出进行分组,例如对于001
我想要的某个类:
payment_method1, sumofpayment_method1, payment_method2, sumofpayment_method2, payment_method3, sumofpayment_method3
在一行中。
在 Postgres 9.1 中有可能吗?
更新:
表定义如下:-
您正在寻找crosstab()
附加模块 tablefunc提供的功能。
那么您的函数可能如下所示:
SELECT * FROM crosstab(
'SELECT class, payment_method, sum(debit - credit) AS saldo
FROM tbl
GROUP BY 1,2
ORDER BY 1,2'
,$$VALUES
('payment_method1'::text), ('sumofpayment_method1')
, ('payment_method2'), ('sumofpayment_method2')
, ('payment_method3'), ('sumofpayment_method3')$$
)
AS ct (class text
, payment_method1 numeric, sumofpayment_method1 numeric
, payment_method2 numeric, sumofpayment_method2 numeric
, payment_method3 numeric, sumofpayment_method3 numeric);
Run Code Online (Sandbox Code Playgroud)
我正在使用您提到的所有 6 种“类型”。好吧,我看到其中只有一半实际上是用作类型的。无论哪种方式,请替换您的实际类型。
有关 SO 的相关答案中的更多详细信息、链接和解释。
归档时间: |
|
查看次数: |
1501 次 |
最近记录: |