Suppose I have a table with four columns: ID, ParentID, Timestamp, Value. The ParentID changes the meaning of value. I need to return all the entries from this table where their ParentID = 1 and their Timestamp is within the Timestamps of the items in the table where ParentID = 2 and those items with ParentID.Value > 10.
For example, here is some data:
ID ParentID TimeStamp Value
1 1 51 1
2 2 52 11
3 1 53 2
4 1 54 3
5 2 55 9
6 1 56 4
7 2 57 12
8 1 58 5
9 1 53.5 1
I need a query that returns me those rows with IDs 3, 4, 8, and 9. What would this query look like in SQL or LINQ? Is it permissible to join on yourself and would you use that approach here? I’m stuck on how to determine the timestamp ranges. I’m using Sqlite. Thanks.
Clarification: I want to filter by the most recent (judged by timestamp) row with ParentID = 2.
This ugly and slow query finds per each ParentID = 1 row adequate ParentID = 2 row and checks if Value is greather than 10; if so, outputs row:
This is worth running only once in context of updating a table after a schema change. If you could change ParentID to really be a ParentID (that is, connect record hierarchically) query would become trivial:
ParentID would, of course, had to be found prior to insert and there would be some mathematics involved if business model allows for out of order inserts. If all you expect is simple append of timestamps, this would be the simplest solution.
There is Sql Fiddle live test of this query.