Search code examples
mysqlselectrowsskip

MySql select first rows in every hour, skip rows next 5 minutes


i'm trying to Select only first Rows from Hour as Example as Datetime optional every 2 Hours/3Hours

2020-09-30 09:37:04 SELECT
2020-09-30 09:37:04 SELECT
2020-09-30 09:45:04 SKIP
2020-09-30 09:45:04 SKIP
2020-09-30 09:54:04 SKIP
2020-09-30 10:37:04 SELECT

on other Side i think have a Solution, but its not Work.. maybe Wrong Equal to VAR ?

SET @prev=0;
SELECT `Date`,@prev, @prev:=UNIX_TIMESTAMP(`Date`) 
FROM `tab`
WHERE FLOOR(UNIX_TIMESTAMP(`Date`)/3600)%2 AND UNIX_TIMESTAMP(`Date`)= @prev;```

Solution

  • With NOT EXISTS:

    select t.* from tab t
    where not exists (
      select 1 from tab 
      where date_format(date, '%Y%m%d%H') = date_format(t.date, '%Y%m%d%H')
        and date < t.date
    )
    

    or with RANK() window function:

    select date
    from (
      select date,
        rank() over (partition by date_format(date, '%Y%m%d%H') order by date) rnk
      from tab
    ) t
    where t.rnk = 1
    

    See the demo.
    Results:

    > | date                |
    > | :------------------ |
    > | 2020-09-30 09:37:04 |
    > | 2020-09-30 09:37:04 |
    > | 2020-09-30 10:37:04 |