group结果在一行中具有相似的id

时间:2017-04-20 13:46:26

标签: sql postgresql

我有以下SQL查询:

SELECT 
cat,
CASE WHEN CCR.id_invoice_type = 52 THEN CCR.amount END earn,
CASE WHEN CCR.id_invoice_type = 54 THEN CCR.amount END expend,

FROM fac_invoices CCR
GROUP BY CCR.cat, CCR.id_invoice_type , CCR.amount
ORDER BY CCR.cat

具有以下结果:

cat earn    expend
=======================
3   50,4    (null)
3   (null)  (null)
3   (null)  35
5   160,7   (null)
5   (null)  (null)
5   (null)  35
10  50,4    (null)
10  (null)  (null)
10  (null)  35

但我想获得当前的结果

cat earn    expend
=======================
3   50,4    35
5   160,7   35
10  50,4    35

正如你所看到的,我试图对这些字段进行分组,但它不起作用。我的查询有什么问题?或者我应该使用哪些其他功能来获得所需的结果?

提前致谢。

2 个答案:

答案 0 :(得分:0)

您需要简化GROUP BY。您只需要每cat行一行,因此这应该是GROUP BY中的唯一键。实现目标的一种方法是string_agg()

SELECT cat,
       STRING_AGG(CASE WHEN CCR.id_invoice_type = 52 THEN CCR.amount END) as earn,
       STRING_AGG(CASE WHEN CCR.id_invoice_type = 54 THEN CCR.amount END) as expend
FROM fac_invoices CCR
GROUP BY CCR.cat
ORDER BY CCR.cat;

MAX()也适用于您的情况。

SELECT cat,
       MAX(CASE WHEN CCR.id_invoice_type = 52 THEN CCR.amount END) as earn,
       MAX(CASE WHEN CCR.id_invoice_type = 54 THEN CCR.amount END) as expend
FROM fac_invoices CCR
GROUP BY CCR.cat
ORDER BY CCR.cat;

答案 1 :(得分:0)

您应该使用string_agg(),然后使用

CASE WHEN CCR.id_invoice_type = 52 THEN string_agg(CCR.amount,',') END earn,