将行值转换为单列数组(或多列)

convert row values to single column as array (or to multiple columns)

我有 3 张桌子,例如 emptable, tax (1:m with emptable using empid), deductions (1:m with emptable using empid)

========== emptbl ==========
empid, totaltax, totaldeductions...
001, 100, 50

========== tax ========== taxes can be 1 line item per empid or many line items
empid, date, tax_line_item, tax, tax_type...
001, 12-15-2021, 1, 25, A
001, 12-15-2021, 2, 30, B
001, 12-15-2021, 3, 25, C

========== deductions ========== deductions can be 1 line item per empid or many line items
empid, date, ded_line_item, deduction, deduction_type...
001, 12-15-2021, 1, 12.5, W
001, 12-15-2021, 2, 12.5, 401
001, 12-15-2021, 3, 20, I
001, 12-15-2021, 4, 5, B

Desired result

========== RESULT ==========
empid, totaltax, totaldeductions, taxes (as array), tax_type , deductions (as array), deduction_type
001,   100,      50,              25,       A,        12.5,        W
                                  30        B,        12.5,        401
                                  25        C,        20,          I
                                                      5,           B

如果我使用 emptable 和 tax,我会得到 1 行和 taxes 列作为数组,这是我想要实现的,但是当我加入 3 个表并使用 array_agg 获得结果时#2,我得到 12 行 (1x3x4) 而不是总共 4 行。

有什么方法可以得到想要的结果。我感谢任何关于如何实现它的线索。

select a.empid,a.totaltax, a.totaldeductions,string_agg(distinct b.tax::text,',') as taxes , string_agg(distinct c.ded::text,',') as deductions 
from emptbl a, tax b, deductions c
where a.empid=b.empid and b.empid=c.empid
group by a.empid,a.totaltax, a.totaldeductions

我不确定 distinct,但我认为这应该有效。

考虑以下方法

select empid, totaltax, totaldeductions, taxes, deductions
from emptbl e 
left join (
  select empid, array_agg(t.tax order by tax_line_item) taxes
  from tax t group by empid
) using (empid)
left join (
  select empid, array_agg(t.deduction order by ded_line_item) deductions
  from deductions t group by empid
) using (empid)

如果应用于您问题中的示例数据 - 输出为