我有很多像這樣的表:(id,user_id,object_id)。我經常對「有多少用戶有一個對象?有多少個有兩個?」等問題感興趣。並希望看到分配。如何在不使用子查詢的情況下從連接表中獲取計數的直方圖?
答案很明顯,這個樣子:
select x.ucount, count(*)
from (select count(*) as ucount from objects_users group by user_id) as x
group by x.ucount
order by x.ucount;
這產生的結果,如:
ucount | count
-------|-------
1 | 15
2 | 17
3 | 23
4 | 104
5 | 76
7 | 12
使用子查詢在這裏感覺不雅給我,我想弄清楚如何產生沒有相同的結果。此外,如果您試圖提問的問題稍微複雜一些,則會將更多信息傳遞給子查詢。例如,如果你想要的數據進一步由用戶的創建日期進行分組:
select
x.ucount,
(select cdate from users where id = x.user_id) as cdate,
count(*)
from (
select user_id, count(*) as ucount
from objects_users group by user_id
) as x
group by cdate, x.ucount,
order by cdate, x.ucount;
是否有某種方式來避免子查詢的爆炸?我想最終我的反對意見是審美的,但它使查詢很難閱讀,也很難寫。
您正在使用什麼RDBMS和版本? – Lamak 2011-03-21 06:04:54
我使用postgresql9,但我試圖避免任何postgres主義。讓我知道,如果我讓一些滑過:-) – 2011-03-21 16:53:47