此方法使用ROW_NUMBER窗函數升序排序由類型分組的食用食品的數量,以確定吃得最少。如果存在平局,則將選擇最少的類型中的任意一個。使用RANK就像在@ htf的解決方案中發佈一樣,將返回所有關係。
select userid, type from (
select t3.userid, t2.type, count(*) as eaten,
row_number() over(partition by t3.userid order by count(t3.food) asc) AS r
from t3 join t2 on t3.food=t2.food
group by 1,2
) least
where r=1
假設你想要的東西了T1的將是這樣的:
select t1.name, least.type from (
select t3.userid, t2.type, count(*) as eaten,
row_number() over(partition by t3.userid order by count(t3.food) asc) AS r
from t3 join t2 on t3.food=t2.food
group by 1,2
) least
join t1 on t1.userid=least.userid
where least.r=1
這裏是一個辦法做到這一點沒有窗函數。這樣,使用自連接的類型吃掉識別至少吃了計數和過濾等更頻繁地吃的食物(加T1假設你想要一些外地離開那裏):
with type_counts as (
select t3.userid, t2.type, count(*) as eaten,
from t3 join t2 on t3.food=t2.food
group by 1,2
)
select t1.username, tc.userid, tc.type
from type_counts tc
inner join (select userid, min(eaten) as eaten from type_counts group by 1) mintc
on tc.userid=mintc.userid and tc.eaten=mintc.eaten
inner join t1 on t1.userid=tc.userid
該版本將包括領帶最少吃。
當你想要sql查詢時,請發佈一些示例數據和預期的結果,並告訴我們你儘可能地嘗試過了。 – Blank
t4包含解決方案。 – wildplasser
你不必重新發明輪子,這是一個典型的[標籤:最大n組]查詢(這裏有[很多解決方案](http://stackoverflow.com/questions/tagged/postgresql) + most-n-per-group?sort = votes)),只需要顛倒操作符以找到* least *,而不是* * *。 – pozs