How to do a Postgresql subquery in select clause with join in from clause like SQL Server?

前端 未结 5 1969
野性不改
野性不改 2021-01-30 04:00

I am trying to write the following query on postgresql:

select name, author_id, count(1), 
    (select count(1)
    from names as n2
    where n2.id = n1.id
             


        
5条回答
  •  一向
    一向 (楼主)
    2021-01-30 04:20

    select n1.name, n1.author_id, cast(count_1 as numeric)/total_count
      from (select id, name, author_id, count(1) as count_1
              from names
              group by id, name, author_id) n1
    inner join (select distinct(author_id), count(1) as total_count
                  from names) n2
      on (n2.author_id = n1.author_id)
    Where true
    

    used distinct if more inner join, because more join group performance is slow

提交回复
热议问题