如何通过两个字段计数并加入其他表Postgres?

时间:2017-12-11 15:04:41

标签: sql postgresql postgresql-9.6

我有两个表,一个表用户和第二个与用户完成的事务相关的表事务。我想做一个查询,按名称和日期给我计数,用户表中的字段。我该怎么办?

Table user:

Name   Id Card
-----------------
Alex   01  N
James  02  Y


Table transaction:

Name   Date
-----------------
Alex   01/07/2012
Alex   01/12/2012
James  01/08/2012
Alex   01/07/2012
Alex   01/12/2012
James  01/07/2012
James  01/07/2012

我想要像这样:

Name   Date         Transactions    ID   Card
---------------------------------------------
Alex   01/07/2012   2               01   N
Alex   01/12/2012   2               01   N
James  01/08/2012   1               02   Y 
James  01/07/2012   2               02   Y

首先,我尝试用两列来计算:

select name, date, count(name, date) from pm_transaction GROUP BY (name,date)
select count(distinct(machine, date)) from pm_transaction

但它不起作用,我尝试了很多组合,但没有人工作

2 个答案:

答案 0 :(得分:1)

试试这个

select tb1.name, tb2.date , tb2.transaction , tb1.Id, tb1.card from tbUser as tb1 inner join (select date, name, count(date) as transaction from tbTransaction group by date) as tb2 on tb1.name = tb2.name

答案 1 :(得分:0)

这看起来像简单的聚合任务。只需检查并更正表连接条件和表名:

select u.name, t.date, count(1) as transactions, u.id, u.card
from transaction t
join user_table u on u.name = t.name
group by u.name, t.date, u.id, u.card;