在Postgres中混合INs和Cross Table查询

时间:2014-05-22 13:15:06

标签: sql postgresql join

我是Postgres的新手。我有一个涉及4个表的查询。我的表格如下所示:

User            Account             Transaction         Action
----            -------             -----------         ------
ID              ID                  ID                  ID
Name            UserID              AccountID           AccountID
                                    Description         Description

对于每个用户,我都想弄清楚:他们拥有多少个帐户,以及在所有帐户中执行了多少次交易和操作。换句话说,我试图生成一个查询,其结果如下所示:

User            Accounts          Transactions            Actions
----            --------          ------------            -------
Bill            2                 27                      7
Jack            1                 7                       0
Joe             0                 0                       0

如何编写这样的查询?目前,我正在尝试以下方法:

SELECT
  u.Name,
  (SELECT COUNT(ID) FROM Account a WHERE a.UserID = u.ID) as Accounts
FROM
  User u

现在,我被困了。

2 个答案:

答案 0 :(得分:1)

未经测试,我会选择这样的东西。

select
u.Name,
count(distinct a.ID) as Accounts,
count(distinct t.ID) as Transactions,
count(distinct ac.ID) as Actions
from User u
left join Account a on u.ID = a.UserID
left join Transaction t on t.AccountID = a.ID
left join Action ac on ac.AccountId = a.Id
group by u.Name

答案 1 :(得分:0)

可能意图:

SELECT u.name, u.id
      ,COALESCE(x.accounts, 0)     AS accounts
      ,COALESCE(x.transactions, 0) AS transactions
      ,COALESCE(x.actions, 0)      AS actions
FROM  users u
LEFT  JOIN (
   SELECT a.userid  AS id
         ,count(*)  AS accounts
         ,sum(t.ct) AS transactions
         ,sum(c.ct) AS actions
   FROM   account a
   LEFT   JOIN (SELECT accountid AS id, count(*) AS ct FROM transaction GROUP BY 1) t USING (id)
   LEFT   JOIN (SELECT accountid AS id, count(*) AS ct FROM action      GROUP BY 1) c USING (id)
   GROUP  BY 1
   ) x USING (id);

先分组,稍后加入。如果你想要整张桌子,这是迄今为止最快,最干净的。

SQL Fiddle(以@Raphaël提供的方式为基础,美化)。

除此之外:我在第一个版本中绊倒了你的命名惯例。