我试图写下面的查询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,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,count(1) as count_1 from names group by id,author_id) n1 inner join (select 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可用于加入第二个子查询。也许别人会想出一个更好的解决方案。
分享和享受。
原文地址:https://www.jb51.cc/postgresql/193405.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。