分组并按多列汇总

时间:2018-11-23 10:07:31

标签: sql postgresql

示例表

帐户

enter image description here

用户

enter image description here

tproject

enter image description here

我想要实现的目标:

accountName count(u.id) count(p.id)
-----------------------------------
Account A   1           1
Account B   1           1
Account C   2           3

换句话说,我希望一个查询将这些表连接在一起,并计算每个帐户的用户和项目的费用

我尝试过:

SELECT
    a.name as "accountName",
    count(u.name),
    count(p.id)
FROM "taccount" a
INNER JOIN "tuser" u ON u.account_id = a.id
INNER JOIN "tproject" p ON p.admin_id = u.id
GROUP BY u.name, a.name, p.id

但是它不是按帐户分组。给我以下结果

enter image description here

有什么建议吗?

4 个答案:

答案 0 :(得分:2)

您可以在下面尝试

SELECT
    a.name as "accountName",
    count(distinct u.name),
    count(p.id)
FROM "taccount" a
INNER JOIN "tuser" u ON u.account_id = a.id
INNER JOIN "tproject" p ON p.admin_id = u.id
GROUP BY  a.name

答案 1 :(得分:1)

通过列名更改您的组

SELECT
    a.name as "accountName",
    count(distinct u.account_id),
    count(p.id)
FROM "taccount" a
INNER JOIN "tuser" u ON u.account_id = a.id
INNER JOIN "tproject" p ON p.admin_id = u.id
GROUP BY  a.name

答案 2 :(得分:1)

当您执行Aggregate函数并且如果没有列Group By时,您必须放入Aggregate,因为SELECT a.name as "accountName", count(distinct u.name), count(p.id) FROM "taccount" a INNER JOIN "tuser" u ON u.account_id = a.id INNER JOIN "tproject" p ON p.admin_id = u.id GROUP BY a.name 函数对一组行并返回单行。

Group By

所以您只需要"accountName"var array = ["abc",["def,ghi"]]; var res = array.toString().split(',');

答案 3 :(得分:0)

这将起作用:

select a.name,count(u.id),count(p.id) from 
taccount a,tuser b, tproject where
a.id=b.account_id and
b.id=c.admin_id
group by a.name;