Search code examples
sqldashdb

SQL select only one item which meets condition


I have a very narrow table: DATA, ID, LAT, LNG, TIME. (https://gyazo.com/52b268c00963ed12ba85c6765f40bf63)

And I want to select the newest data for each different ID. I was using query like

SELECT * 
  FROM name_of_table 
 WHERE TIME > my_given_time;

but it selects TOTALLY all datas and not only data for each different id which meets the condition.

Could somebody please help me write the query?

Thank you for any help. :)

EDIT

The final look of my working query looks like:

SELECT * FROM (SELECT * FROM (SELECT ROW_NUMBER() OVER (PARTITION BY ID ORDER BY TIME DESC) AS ROWNUMBER, * FROM my_table) WHERE ROWNUMBER = 1) WHERE TIME > my_time;

Thanks everyone for help


Solution

  • How about something like this

    SELECT ID, DATA 
    FROM (
     SELECT ROW_NUMBER() OVER (PARTITION BY ID ORDER BY TIME DESC) AS ROWNUMBER, ID, DATA
     FROM name_of_table)
    WHERE ROWNUMBER = 1; 
    

    For these dummy records

    INSERT INTO name_of_table (ID, TIME, DATA) VALUES('test',1230,16);
    INSERT INTO name_of_table (ID, TIME, DATA) VALUES('test2',1235,10);
    INSERT INTO name_of_table (ID, TIME, DATA) VALUES('test',1234,20);
    

    the query returns the data value for the largest timestamp for each ID

      ID    DATA
      ----- ----
      test    20
      test2   10