2010-06-09 86 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)