我坚持使用一些SQL查询。假设我有如下数据库表:
user_hash | created_on
xxx 1
xxx 10
xxx 100
yyy 2
yyy 20
yyy 200
除了每行created_on
具有最低user_hash
值的行之外,我需要选择所有行,所以我希望结果像这样:
user_hash | created_on
xxx 10
xxx 100
yyy 20
yyy 200
我知道如何使用偏移量为特定的user_hash
选择它:
SELECT *
FROM users
WHERE user_hash = ‘xxx’
ORDER BY created_on ASC
OFFSET 1 ROW;
但是我无法弄清楚如何在一个查询中对所有user_hash
执行此操作。我正在尝试进行分组,子查询和联接,但是没有任何效果。有人可以帮我吗?
答案 0 :(得分:4)
假设您的数据库中有ROW_NUMBER
,我们可以在这里尝试使用:
WITH cte AS (
SELECT *, ROW_NUMBER() OVER (PARTITION BY user_hash ORDER BY created_on) rn
FROM yourTable
)
SELECT user_hash, created_on
FROM cte
WHERE rn > 1;
答案 1 :(得分:0)
一种方法使用相关的子查询:
select t.*
from t
where t.created_on > (select min(t2.created_on)
from t t2
where t2.user_hash = t.user_hash
);