我有一个sql表:
DATE USER FLAGGED COMMAND
1 Alice 0 sudo gparted
2 Bob 1 sudo
3 Bob 0 mv
4 Alice 1 sudo rm -rf
5 Charlie 1 sudo chown
我想选择用户的最后标记操作
DATE USER FLAGGED COMMAND
2 Bob 1 sudo
4 Alice 1 sudo rm -rf
5 Charlie 1 sudo chown
我试过
select DATE, USER, REQUEST
from
(
select DATE, USER, REQUEST, FLAGGED
row_number() over(partition by USER order by date desc) rn
from USERDATA
) src
where rn = 1 and FLAGGED = 1
但它总结了鲍勃。我怎么能。添加" FLAGGED = 1"的正确方法是什么?到SQL请求?
答案 0 :(得分:1)
将标记条件移动到子查询,因此只检索标记为= 1的行,您可以选择rn = 1条件的最新行。
select DATE, USER, REQUEST
from
(
select DATE, USER, REQUEST, FLAGGED,
row_number() over(partition by USER order by date desc) rn
from USERDATA
where flagged = 1
) src
where rn = 1
答案 1 :(得分:1)
您还可以使用通用MAX
查询:
select DATE, USER, REQUEST
from USERDATA
WHERE (date, user) IN (
select MAX(DATE) as date, USER
from USERDATA
where flagged = 1
group by user
)
AND flagged = 1
但是,请注意,如果有两个用户条目具有相同的日期是MAX,则可能会返回重复...您可以通过在外部SELECT上使用MIN或MAX来避免这种情况。
答案 2 :(得分:0)
此处首先为用户选择最新条目,然后删除未标记的条目。相反,您应首先选择所有FLAGGED条目,然后找到最新的条目。这段代码应该有用。
select DATE, USER, REQUEST
from
(
select DATE, USER, REQUEST, FLAGGED
row_number() over(partition by USER order by DATE desc) rn
from USERDATA WHERE FLAGGED = 1
) src
where rn = 1