So I have the following query
select * from sval where fid = 4044 and val = 'True';
The output of the above is:
sval table
id fid timestamp val
1 4044 2019-01-22 00:00:00.000 True
2 4044 2020-02-22 00:00:00.000 True
3 4044 2023-02-02 00:00:00.000 True
1 4044 2020-05-28 00:00:00.000 True
4 4044 2023-05-03 00:00:00.000 True
....
I have another query:
select * from ival where fid = 3994 and val=0
The result of the query is:
ival table
id fid timestamp val
1 3994 2019-01-22 00:00:00.000 0
2 3994 2020-02-22 00:00:00.000 0
3 3994 2023-02-02 00:00:00.000 0
1 3994 2020-05-28 00:00:00.000 0
4 3994 2023-05-03 00:00:00.000 0
I am trying to achieve 2 things:
- I need to filter the first table to remove duplicates
id
‘s and only keep the ‘earliest’id
, i.e. the one with the earliest timestamp. - From this filtered list, I need to return a list of all the
id
‘s in theival
table that have the SAMEtimestamp
as the result of 1)
2
Answers
If all you want to do is get the row with the least value in a group, you’ll want to use
column = MIN(column) OVER(PARTITION BY groupingexpression)
somewhere in the process.Here is one way to do this:
Use a common table expression (CTE) along with the ROW_NUMBER() function to assign a row number based on the timestamp for each fid. From ths, we can select the rows with row numbrs equal to 1 to get the earliest id for each fid.
We use the same approach as before, but we also join it with the ival table to get the ids with the same timestamps.
Try it here