开发者

Preventing Max function from using timestamp as part of criteria on a date column in PL/SQL

开发者 https://www.devze.com 2023-03-10 22:14 出处:网络
If I query: select max(date_created) date_created on a datefield in PL/SQL (Oracle 11g), and there are records that were created on the same date but at different times, Max() returns only the late

If I query:

select max(date_created) date_created

on a datefield in PL/SQL (Oracle 11g), and there are records that were created on the same date but at different times, Max() returns only the latest times on that date. What I would like to do is have the times be ignored and return ALL records that match the max date, regardless of their associated timestamp in that column. What is the best practice for doing this?

Edit: what I'm looking to do is return all records for the most recent date that matches my criteria, regardles开发者_如何学Gos of varying timestamps for that day. Below is what I'm doing now and it only returns records from the latest date AND time on that date.

    SELECT r."ID",
    r."DATE_CREATED"
  FROM schema.survey_response r
  JOIN
    (SELECT S.CUSTOMERID ,
      MAX (S.DATE_CREATED) date_created
    FROM schema.SURVEY_RESPONSE s
    WHERE S.CATEGORY IN ('Yellow', 'Blue','Green')
    GROUP BY CUSTOMERID
    ) recs
  ON R.CUSTOMERID    = recs.CUSTOMERID
  AND R.DATE_CREATED = recs.date_created
  WHERE R.CATEGORY  IN ('Yellow', 'Blue','Green')

Final Edit: Got it working via the query below.

SELECT r."ID",
    r."DATE_CREATED"
  FROM schema.survey_response r
  JOIN
    (SELECT S.CUSTOMERID ,
      MAX (trunc(S.DATE_CREATED)) date_created
    FROM schema.SURVEY_RESPONSE s
    WHERE S.CATEGORY IN ('Yellow', 'Blue','Green')
    GROUP BY CUSTOMERID
    ) recs
  ON R.CUSTOMERID    = recs.CUSTOMERID
  AND trunc(R.DATE_CREATED) = recs.date_created
  WHERE R.CATEGORY  IN ('Yellow', 'Blue','Green')


In Oracle, you can get the latest date ignoring the time

SELECT max( trunc( date_created ) ) date_created
  FROM your_table

You can get all rows that have the latest date ignoring the time in a couple of ways. Using analytic functions (preferrable)

SELECT *
  FROM (SELECT a.*,
               rank() over (order by trunc(date_created) desc) rnk
          FROM your_table a) 
 WHERE rnk = 1

or the more conventional but less efficient

SELECT *
  FROM your_table
 WHERE trunc(date_created) = (SELECT max( trunc(date_created) )
                                FROM your_table)
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号