【问题标题】:Count matching entries in a database row unless the row is empty计算数据库行中的匹配条目,除非该行为空
【发布时间】:2017-10-11 15:13:38
【问题描述】:

计算一行中连续(特定)匹配的条目,但如果介于两者之间,则从头开始。

我的想法是查看某人在一段时间内(在我的情况下为 15 分钟)进行了多少次登录尝试并采取相应的行动。例如(简表):

Row: User_id | Loginstatus | Timestamp
     5           Attempt        most recent 
     5           Attempt        .
     5           Logoff         .
     5           Login          .
     5           Attempt        .
     5           Attempt        .
     5           Attempt        . 
     5           Attempt        .
     5           Logoff         .
     5           Login          .
     5           Logoff         . 
     5           Login          .

我的选择现在应该产生:2

到目前为止我得到了什么:

select count(Loginstatus) Result  from Userlog
where User_Id = 5
and Loginstatus = 'ATTEMPT'
and Timestamp > Systimestamp - Interval '15' Minute;

但不幸的是,这会计算所有尝试。我很高兴为您提供任何帮助,并提前感谢您

【问题讨论】:

  • 用您正在使用的数据库标记您的问题。
  • 对不起,我忘了提。感谢您的提示

标签: sql database select oracle-sqldeveloper


【解决方案1】:

您可以使用行号的差异来识别相邻的序列:

select user_id, count(*) as num_consecutive
from (select ul.*,
             row_number() over (partition by user_id order by timestamp) as seqnum_u,
             row_number() over (partition by user_id, loginstatus order by timestamp) as seqnum_us

      from Userlog ul
      where User_Id = 5 and Timestamp > Systimestamp - Interval '15' Minute;
     ) ul
where Loginstatus = 'ATTEMPT'
group by user_id, (seqnum_u - seqnum_us);

如果你想要一个值,你可以添加:

order by num_consecutive desc
fetch first 1 row only

【讨论】:

  • 完美!非常感谢您,先生:)
【解决方案2】:

您需要使用GROUP BY:

SELECT [LoginStatus]=MAX(Loginstatus), [Count]=count(Loginstatus) 
FROM Userlog
WHERE User_Id = 5
AND Loginstatus = 'ATTEMPT'
AND Timestamp > Systimestamp - Interval '15' Minute;
GROUP BY (Loginstatus)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-02
    • 2021-08-03
    • 2011-05-24
    相关资源
    最近更新 更多