获取不同数据的SQL语句

获取不同数据的SQL语句,sql,postgresql,greatest-n-per-group,Sql,Postgresql,Greatest N Per Group,我正在使用PostgreSQL。在我的应用程序中,用户可以创建多个配置文件,我希望选择每个用户创建的最后一个不同的非活动配置文件。此外,如果有一个活动的配置文件属于该用户,它不应该从该用户选择任何配置文件-这是我的困难部分 为了得到以下结果,我应该使用哪种SQL语句 ID | user_id | name | active 1 | 1 | Profile 1 | f 2 | 1 | Profile 2 | t 3 | 2 | Profile 3

我正在使用PostgreSQL。在我的应用程序中,用户可以创建多个配置文件,我希望选择每个用户创建的最后一个不同的非活动配置文件。此外,如果有一个活动的配置文件属于该用户,它不应该从该用户选择任何配置文件-这是我的困难部分

为了得到以下结果,我应该使用哪种SQL语句

ID | user_id | name      | active
1  | 1       | Profile 1 | f
2  | 1       | Profile 2 | t
3  | 2       | Profile 3 | f
4  | 2       | Profile 4 | f
5  | 3       | Profile 5 | f
distinct on语法在这方面非常有效:

4  | 2       | Profile 4 | f
5  | 3       | Profile 5 | f
编辑:

要避免激活配置文件,可能更容易转到分析函数:

select distinct on (user_id) id, user_id, name, active
from t
where active = 'f'
order by user_id, id desc;
我会和你结合。 假设活动的布尔类型正确:

select distinct on (user_id)
    id, user_id, name, active
from
    t
    inner join
    (
        select user_id
        from t
        group by user_id
        having not bool_or(active)
    ) s using(user_id)
order by user_id, id desc

可能是最快和最干净的。

是的,希望它也能选择具有活动配置文件的用户所在的行。@ErenCAY。是的,这使得在上使用distinct变得很困难。请参阅已编辑的版本。@GordonLinoff当active='f'然后1或0结束时,最好将bool\u或active用作anyActive,而不是maxcasenumActives@GordonLinoff另外,您不需要按用户id(活动)进行分区。按用户id分区就足够了。@GordonLinoff可以使用更多的标准构造,但当active='f'然后1或0以numActives结尾时,仍然在MAXSCASE中保存了一个错误。如果任何记录有活动='f',它将返回1。您需要在激活时使用case,然后使用1或0结束
select distinct on (user_id)
    id, user_id, name, active
from
    t
    inner join
    (
        select user_id
        from t
        group by user_id
        having not bool_or(active)
    ) s using(user_id)
order by user_id, id desc
SELECT DISTINCT ON (user_id)
       id, user_id, name, active
FROM   profiles p
WHERE  NOT EXISTS (
   SELECT 1 FROM profiles
   WHERE  user_id = p.user_id
   AND    active               -- exclude users with any active profiles
   )
ORDER  BY user_id, id DESC;