【问题标题】:How to use join with aggregate function in postgresql?如何在 postgresql 中使用 join 和聚合函数?
【发布时间】:2017-08-01 05:50:34
【问题描述】:

我有 4 张桌子

表 1

id    | name    
1     | A
2     | B

表2

id    | name1    
1     | C
2     | D

Table3

id    | name2    
1     | E
2     | F

Table4

id    | name1_id    | name2_id    | name3_id        
1     | 1           | 2           | 1
2     | 2           | 2           | 2
3     | 1           | 2           | 1
4     | 2           | 1           | 1
5     | 1           | 1           | 2
6     | 2           | 2           | 1
7     | 1           | 1           | 2
8     | 2           | 1           | 1
9     | 1           | 2           | 1
10    | 2           | 2           | 1

现在我想用 4 连接所有表并获得这种类型的输出

name    | count
{A,B}   | {5, 5}
{C,D}   | {5, 6}
{E,F}   | {7, 3}

我试过了

select array_agg(distinct(t1.name)), array_agg(distinct(temp.test))
from  
 (select t4.name1_id, (count(t4.name1_id)) "test" 
    from table4 t4 group by t4.name1_id
) temp
join table1 t1
on temp.name1_id = t1.id

我正在努力实现这一目标。任何人都可以帮助我。

【问题讨论】:

  • 请标记适当的数据库系统。您不能同时使用所有不同的数据库系统
  • 好的,我编辑了我的问题
  • 我试过这个... select array_agg(distinct(rt.name)), array_agg(distinct(temp.test)) from (select f.resource_type_id, (count(f.resource_type_id)) " test" from planner.resource_entity f join planner.resource_type ft on f.resource_type_id = ft.id group by f.resource_type_id) temp join planner.resource_type rt on temp.resource_type_id = rt.id
  • 实际上我为问题创建了一个演示表。

标签: postgresql postgresql-9.1 postgresql-9.3 postgresql-9.2 postgresql-9.4


【解决方案1】:

分别计算每个表的计数并将结果合并:

select 
    array_agg(name order by name) as name, 
    array_agg(count order by name) as count
from (
    select 1 as t, name, count(*)
    from table4
    join table1 t1 on t1.id = name1_id
    group by name
    union all
    select 2 as t, name, count(*)
    from table4
    join table2 t2 on t2.id = name2_id
    group by name
    union all
    select 3 as t, name, count(*)
    from table4
    join table3 t3 on t3.id = name3_id
    group by name
    ) s
group by t;

 name  | count 
-------+-------
 {A,B} | {5,5}
 {C,D} | {4,6}
 {E,F} | {7,3}
(3 rows)    

【讨论】:

  • 如果我使用的列数据类型是表4中的数组,那么。
猜你喜欢
  • 2021-07-29
  • 2018-06-29
  • 1970-01-01
  • 1970-01-01
  • 2018-07-10
  • 1970-01-01
  • 1970-01-01
  • 2013-12-31
  • 2011-05-26
相关资源
最近更新 更多