如何做一个Postgresql子查询的select子句与像SQL Server一样的join子句?

我试图写下面的查询postgresql:

select name, author_id, count(1), 
    (select count(1)
    from names as n2
    where n2.id = n1.id
        and t2.author_id = t1.author_id
    )               
from names as n1
group by name, author_id

这将肯定工作在Microsoft SQL Server,但它根本不在postegresql。我读了它的文档有点,它似乎我可以重写它:

select name, author_id, count(1), total                     
from names as n1, (select count(1) as total
    from names as n2
    where n2.id = n1.id
        and n2.author_id = t1.author_id
    ) as total
group by name, author_id

但是这会在postegresql上返回以下错误:“FROM中的子查询不能引用同一查询级别的其他关系”。所以我被卡住了。有谁知道我怎么能实现呢?

谢谢

我不知道我完全理解你的意图,但也许以下将接近你想要的:

select n1.name, n1.author_id, count_1, 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 id, author_id, count(1) as total_count
              from names
              group by id, author_id) n2
  on (n2.id = n1.id and n2.author_id = n1.author_id)

不幸的是,这增加了按照id以及name和author_id对第一个子查询进行分组的要求,我认为这是不需要的。我不知道如何解决,但是,因为你需要有id可用于加入第二个子查询。也许别人会想出一个更好的解决方案。

分享和享受。

http://stackoverflow.com/questions/3004887/how-to-do-a-postgresql-subquery-in-select-clause-with-join-in-from-clause-like-s

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:如何做一个Postgresql子查询的select子句与像SQL Server一样的join子句?