2010-06-09 281 views
43

我试图写的PostgreSQL以下查询:如何在select子句中使用from 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不能引用的同一查询级别的其他关系的子查询”。所以我卡住了。有谁知道我能做到吗?

感谢

+0

其实好像这应该对Postgres的工作(也许6年以前它没有:)) – qwertzguy 2016-08-07 23:00:28

回答

69

我不知道我理解你的意图完美,但也许你想要的东西下面将接近:

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加入第二个子查询中。也许别人会想出更好的解决方案。

分享和享受。

+0

完美的鲍勃,真的有效。非常感谢!我不得不稍微改变一下,因为我不需要与id的连接,只需要author_id。所以最终的查询是: 选择n1.name,n1.author_id,COUNT_1,TOTAL_COUNT 从(选择编号,名称,AUTHOR_ID,计数(1)从名COUNT_1 通过ID,名称,AUTHOR_ID 组)N1 内部连接(选择AUTHOR_ID,计数(1)TOTAL_COUNT 从名字 组由AUTHOR_ID)上(n2.author_id = n1.author_id) 现在,我有这个N2 ,我真正想要的是通过TOTAL_COUNT划分COUNT_1有一个标准化的频率。 = D – 2010-06-09 12:00:40

+0

ops,刚刚意识到sql在这里没有正确格式化。 :( 将给出补充答案 – 2010-06-09 12:02:10

+0

我没有问题里卡多在说'回合,但这个SQL完全解决了我的问题......:D谢谢你! – tftd 2011-03-21 20:22:28

7

我只是回答这里有我需要根据鲍勃·贾维斯答案最终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)