【问题标题】:PostgresSQL - Loop through daily Select statement for end of month reportingPostgresQL - 循环通过每日 Select 语句进行月末报告
【发布时间】:2025-12-05 10:15:01
【问题描述】:

PostgreSQL 9.4.5

我每天晚上 11:55 运行以下 select 语句。我想运行基于硬编码的 start_date 和 end_date 循环通过以下查询的每月查询(或函数)。查询必须每天处理结果。最后,我想看看我们在给定的一个月里有多少迷失的羊。

目的:Lost Sheep- 我们正在寻找尝试登录 MySoftware 并且一整天都没有成功的用户。

*The IP address is compared against other login attempts that may be successful the rest of the day.  In the event of a login failure, the query should look into the ip address and verify that no successful logins happened from that same IP address within the day.

SELECT  DISTINCT l.username, l.ip
FROM login l
                    WHERE
                        l.ip NOT IN 
                            (SELECT  l.ip
                            FROM login l
                            WHERE 
                                date_trunc('day', l."time") = current_date
                                AND l.succeeded = 'TRUE')
                        AND date_trunc('day', l."time") = current_date
                        AND l.succeeded = 'False'


fields in Table logins
 1. id  -int
 2. username --character varying(255)
 3. ip -- character varying (255)
 4. time -- timestamp without time zone
 5. succeeded -- boolean

【问题讨论】:

    标签: postgresql datetime


    【解决方案1】:
    select date_trunc('day', l.time) as 'day', l.username, l.ip
    from login l
    where date_trunc('month', l.time) = '2015-09-01'
    group by 1, 2, 3
    having not bool_or(succeded)
    

    【讨论】:

    • 感谢您的回复,您的回答让我更加接近。你的建议确实给了我当月所有失败登录的列表......但是,我需要有逻辑来查看用户的“IP地址”并验证来自该IP的用户没有登录当天成功。有时我们的用户忘记了他们的用户名,失败后记住了正确的用户名,然后成功登录。如果您在我的查询中注意到他们提供的逻辑来处理这些登录并将它们从列表中删除。