2

尝试获取具有不同 user_id 的最新活动,按“最新”排序(顺序“id desc”或“created_at desc”):

SELECT DISTINCT ON (id, user_id) id,user_id 
FROM "activities" 
GROUP BY id,user_id 
ORDER BY id desc LIMIT 10

但这会返回 10 个带有以下 user_ids 的结果:

2863, 2863, 2863, 2863, 2863, 2863, 2863, 2863, 2863, 2615

显然,这并不明显。我将如何得到它,使其具有不同的(分组的)user_id?

编辑:也许我解释得不好,我很抱歉。真的很简单,我想要来自唯一 user_id 的最新活动。到最近,我喜欢 created_at ,但 id 也可以。我只想要每个用户一个,没有重复。

再次编辑:意识到第一句话真的让回答者望而却步。很抱歉把每个人都扔在那里,我想要的真的很简单:/。

4

4 回答 4

1

试试这个:

select user_id, array_agg(id) as ids
from activities
group by user_id
having count(*) > 1;

array_agg()函数将组的所有值作为逗号分隔的列表返回。

编辑:

从评论看来,您可能只想要这个:

select distinct user_id
from activities;

或者可能是这个,它只显示那些有重复的用户 ID:

select user_id
from activities
group by user_id
having count(*) > 1;
于 2012-12-24T02:56:51.293 回答
1

我不确定你想要什么,但试试这个:

SELECT id, user_id
FROM (
   SELECT id
        , user_id
        , ROW_NUMBER () OVER (PARTITION BY id
                              ORDER BY user_id DESC) as rn
   FROM "activities"
   ) as xx
WHERE rn = 1
ORDER BY id desc 
LIMIT 10

ROW_NUMBEROLAP 函数将在 的值内分配一个计数器id

于 2012-12-24T03:23:59.077 回答
1

RE: 我想要来自唯一 user_id 的最新活动

SELECT DISTINCT ON (user_id) user_id, created_at
FROM "activities" 
ORDER BY user_id, created_at desc

RE: 那我怎么拿到身份证呢?我还需要身份证

重复使用上面的查询:

with latest_activities as
(
  SELECT DISTINCT ON (user_id) user_id, created_at
  FROM "activities" 
  ORDER BY user_id, created_at desc
)
select l.user_id, l.created_at, array_agg(a.id) as ids
from latest_activities l
join activities a using(user_id)
group by l.user_id, l.created_at
于 2012-12-25T00:16:50.260 回答
1

如果您有一些最新的活动,例如

user_id created_at      id
john    july 4, 2010    1
john    july 4, 2010    2
john    july 12, 2010   3        -- ties with id# 4
john    july 12, 2010   4        -- ties with id# 3
john    july 5, 2010    5
paul    july 13, 2010   6
paul    july 12, 2010   7

使用dense_rank:

with latest_activities as
(
    SELECT user_id, created_at, id,
        dense_rank() 
        over(partition by user_id order by created_at desc) as the_ranking
    FROM activities     
)
select * 
from latest_activities
where the_ranking = 1
order by user_id, id;

上面的查询将显示:

user_id created_at      id 
john    july 12, 2010   3
john    july 12, 2010   4
paul    july 13, 2010   6

如果您希望每个用户的多个 id 仅出现在一行上,请使用group_concat array_agg,它将显示以下内容:

user_id created_at      ids
john    july 12, 2010   3, 4
paul    july 13, 2010   6

数组聚合:

with latest_activities as
(
    SELECT user_id, created_at, id,
        dense_rank() 
        over(partition by user_id order by created_at desc) as the_ranking
    FROM activities     
)
select user_id, created_at, array_agg(id order by id) as ids
from latest_activities
where the_ranking = 1
group by user_id, created_at

请注意,上面的查询也在处理没有关联的数据

现场测试:http ://www.sqlfiddle.com/#!12/c48ec/8

于 2012-12-25T00:35:32.247 回答