计数和内部联接

时间:2017-07-07 16:14:40

标签: sql postgresql

看看这个sql请求:

select distinct erp.users.id 
from erp.users
inner join prod.referral_order_delivered
on erp.users.id= prod.referral_order_delivered.user_id::uuid
inner join erp.orders 
on erp.orders."userId"::uuid= erp.users.id
where
    "paidAt"::date >= '2016-06-07'
    and "paidAt"::date <= '2017-07-07'

假设我得到的结果如下:

id 
2
1
4
5

现在我想计算这些ID的值在表erp.orders

中显示为userId列的值的次数

例如,如果我有erp.orders.userId,那就是:

userId
2
2
1
4
4
5
5
5

我想要回复此请求:

id  number_of_id
2   2
1   1
4   2
5   3

有什么想法吗?

1 个答案:

答案 0 :(得分:4)

您需要使用count()函数和group by子句。它看起来像是:

select 
  erp.users.id
  , count(1)
from 
  erp.users
  inner join prod.referral_order_delivered
    on erp.users.id = prod.referral_order_delivered.user_id::uuid
  inner join erp.orders 
    on erp.orders."userId"::uuid = erp.users.id
where
    "paidAt"::date     >= '2016-06-07'
    and "paidAt"::date <= '2017-07-07'
group by
    erp.users.id