Count and inner join

[亡魂溺海] 提交于 2021-01-27 22:41:36

问题


Look at this sql request:

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'

Let’s say I get a result like this one:

id 
2
1
4
5

Now I wanna count how many times the value of these ids appear as value of the column userId in the table erp.orders

For example, if I have erp.orders.userId which is:

userId
2
2
1
4
4
5
5
5

I want the request that is gonna return this:

id  number_of_id
2   2
1   1
4   2
5   3

Any ideas?


回答1:


You need to use the count() function and a group by clause. It'll look something like:

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


来源:https://stackoverflow.com/questions/44975464/count-and-inner-join

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!