2014-09-22 46 views
0

考慮,列出了一些書的作者如下:PostgreSQL的 - 計數行

Table 

name  bookid 
--------------- 
Alan  1 
Bob   1 
Charlie  2 
David  2 

我想找出一個人有多少合着者擁有他的整本書線。例如,如果小李寫了兩本書,一本與Bob,另一個與查理+大衛,那麼他的總合着者數量應爲3

我想什麼(但不工作):

select t1.name, count(t2.name) 
from table t1, table t2 
where t1.bookid = t2.bookid 

任何幫助球員?非常感激。

+0

那你試試? – 2014-09-22 07:40:38

+0

從表t1中選擇t1.name,count(t2.name),表t2其中t1.bookid = t2.bookid – antikbd 2014-09-22 07:42:43

+0

家庭作業?這是[教程級別資料](http://www.postgresql.org/docs/current/static/tutorial.html)。 – 2014-09-22 07:49:09

回答

1
select t1.name, count(t2.name) 
from table1 t1, table1 t2 
where t1.bookid = t2.bookid 
and t1.name != t2.name 
group by t1.name 

sqlfiddle

+0

也許'count(distinct t2.name)'?同一作者可能會出現很多次 – 2014-09-22 08:19:02

+0

也是最好做一個'left join'。作者可能沒有任何合着者。 – 2014-09-22 08:20:02

-1
SELECT name, count(*) as cnt 
FROM table 
GROUP BY name; 
+0

它將總是返回1作爲此示例中的計數 – 2014-09-22 07:58:57

+0

對於您的表,這將返回1作爲計數,因爲您有兩本書不同的作者。但是如果添加名爲Alan和bookid = 3的新行,Alan將會有2個爲count列。 – 2014-09-22 08:03:13

+0

阿蘭和鮑勃是同一本書的兩位作者。查理和大衛也是。 – 2014-09-22 08:05:35