简体   繁体   English

SQL 查询如果两个日期在组中相同,则按天获取最新项目

[英]SQL query get newest item if two dates are the same in group by day

I'm working on a reporting system where there should only be the newest entry of each day over multiple days returned by my SQL query so that there's no dupes in the report.我正在开发一个报告系统,其中应该只有我的 SQL 查询返回的多天内每天的最新条目,以便报告中没有欺骗。 MY current query works fine in that if there are more than one entry on any given day it will get the newest entry for that day in my INNER JOIN , the problem that I'm facing though is if two created values for a report are exactly the same it returns both entries, I only need one.我当前的查询工作正常,如果在任何一天有多个条目,它将在我的INNER JOIN中获得当天的最新条目,但我面临的问题是,如果报表的两个created值恰好是同样它返回两个条目,我只需要一个。

Here's my query:这是我的查询:

SELECT
    *
FROM
    tlp_consolidated_reports AS ConsolidatedReport
INNER JOIN
(
    SELECT
        DATE(created) AS created_at,
        MAX(created) AS max_created_at
    FROM
        tlp_consolidated_reports
    WHERE
        type = 'commissions'
        AND
        user_id = '33'
        AND
        report_from >= '2022-08-01 00:00:00'
        AND
        report_to <= '2022-08-31 23:59:59'
    GROUP BY DATE(created)
) AS joinedReport
  ON joinedReport.created_at = DATE(ConsolidatedReport.created)
  AND
  joinedReport.max_created_at = ConsolidatedReport.created
WHERE
    ConsolidatedReport.type = 'commissions'
    AND
    ConsolidatedReport.user_id = '33'
    AND
    ConsolidatedReport.report_from >= '2022-08-01 00:00:00'
    AND
    ConsolidatedReport.report_to <= '2022-08-31 23:59:59'
ORDER BY
    ConsolidatedReport.created DESC

I tried added a LIMIT 1 into my INNER JOIN just after the GROUP BY but then this only ever returns one entry over the whole period which isn't right.我尝试在GROUP BY之后将LIMIT 1添加到我的INNER JOIN中,但是这只会在整个期间返回一个条目,这是不正确的。

Example:例子:

Reports:报告:

2022-08-09 21:00:00
2022-08-08 15:00:00
2022-08-07 14:00:00
2022-08-07 14:00:00
2022-08-07 13:00:00

Currently returns目前返回

2022-08-09 21:00:00
2022-08-07 14:00:00
2022-08-07 14:00:00

So the 7th is returning the newest, but because the created is the same, it returns both, how can I limit it to one if this scenario is encountered?所以第7个是返回最新的,但是因为created是一样的,所以它都返回了,如果遇到这种情况,我怎么能限制它为一个呢?

If the creation date is the same, then return any of them?如果创建日期相同,则返回其中任何一个?

WITH data AS (
SELECT *, ROW_NUMBER() OVER(ORDER BY created) AS numb
FROM tlp_consolidated_reports
WHERE
        type = 'commissions'
        AND
        user_id = '33'
        AND
        report_from >= '2022-08-01 00:00:00'
        AND
        report_to <= '2022-08-31 23:59:59'
)
SELECT data.*
FROM data 
JOIN (
    SELECT max(numb) AS numb
    FROM data
    GROUP BY DATE(created)
) AS grData ON data.numb = grData.numb
ORDER BY data.created DESC

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM