小编典典

如何在select子句中使用Post in子句(如SQL Server)在Post子句中进行Postgresql子查询?

sql

我正在尝试在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中的子查询无法引用相同查询级别的其他关系”。所以我被卡住了。有谁知道我能做到这一点吗?

谢谢


阅读 211

收藏
2021-04-15

共1个答案

小编典典

我不确定我是否完全理解您的意图,但以下内容可能与您想要的很接近:

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才能加入第二个子查询。也许其他人会提出更好的解决方案。

分享并享受。

2021-04-15