如何在select子句中使用SQL Server中的from子句joinPostgresql子查询?

我想在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分组的第一个子查询的要求,以及名称和author_id,我不认为是想要的。 我不知道如何解决这个问题,但是,因为你需要有id可以join第二个子查询。 也许别人会想出更好的解决scheme。

分享和享受。

我只是在这里回答了我在上面的评论中发布的基于Bob Jarvis回答所需的最终sql的格式化版本:

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