如果我有桌子...
name | day | showers
-----|-----|--------
John | mon | 1
John | tue | 2
John | wed | 1
Pete | fri | 3
我想归还每人每天淋浴最多的桌子...
name | day | showers
-----|-----|--------
John | tue | 2
Pete | fri | 3
我该怎么做?
我认为我可以做...
SELECT name, day FROM table GROUP BY name WHERE showers=max(showers)
但是由于一天不在group by子句中,所以出现语法错误
答案 0 :(得分:2)
使用distinct on
:
select distinct on (name) t.*
from t
order by name, showers desc;
每个名称仅返回一行。如果要在有关系时重复,则使用rank()
或dense_rank()
:
select t.*
from (select t.*,
rank() over (partition by name order by showers desc) as seqnum
from t
) t
where seqnum = 1;
答案 1 :(得分:1)
您可以使用uncorrelated subquery
。这样也会保持联系
select *
from t
where (name, showers) in (select name, max(showers)
from t
group by name);
也可以表示为correlated subquery
select *
from t t1
where showers= (select max(t2.showers)
from t t2
where t1.name=t2.name);
答案 2 :(得分:0)