Question

I've stucked in making expression, cause i don't even imagine how to do this:

Example table (ignore rotid, not using)

 id  ------   trackid    -----rotid-----userid-----actid

1159 ------ 108980421888 ------ 48 ------  1  ------ 21
1160 ------ 108980421888 ------ 48 ------ 917 ------ 2     
1161 ------ 108980421888 ------ 48 ------ 918 ------ 3     - in result
1162 ------ 108980421888 ------ 48 ------ 919 ------ 4     
1163 ------ 108980421888 ------ 48 ------ 920 ------ 5
1164 ------ 108980421888 ------ 48 ------ 921 ------ 4
1165 ------ 108980421888 ------ 48 ------ 922 ------ 6
1166 ------ 108980421888 ------ 48 ------ 917 ------ 4
1167 ------ 108980421888 ------ 48 ------ 918 ------ 6
1168 ------ 108980421888 ------ 48 ------  1  ------ 7
1169 ------ 108980421888 ------ 48 ------ 918 ------ 8
1170 ------ 108980421888 ------ 48 ------ 920 ------ 5
1171 ------ 108980421888 ------ 48 ------ 922 ------ 4
1172 ------ 108980421888 ------ 48 ------ 918 ------ 5
1173 ------ 108980421888 ------ 48 ------ 920 ------ 6
1174 ------ 108980421888 ------ 48 ------  1  ------ 9
1175 ------ 108980421888 ------ 48 ------  1  ------ 19
1176 ------ 108980421888 ------ 48 ------ 918 ------ 12
1177 ------ 108980421888 ------ 48 ------ 920 ------ 12
1178 ------ 108980421888 ------ 48 ------  1  ------ 15

I need to select all rows which: trackid=trackid, goes after actid=21 and before FIRST actid=5. Actid=3. Packets of rows with idiential trackid comes together. Actid=21 always first in rows packets. Actid=5 always presents in rows packet. Sometimes it could be first row actid=21 and second row actid=5. We don't know exact trackid (trackid=?).

In other words: we need to select all rows with actid=3, but ony after actid=21 and before actid=5, with the same trackid.

And the second query is the same, but we know exact userid.

Thanks for advance!

Was it helpful?

Solution

For the data in your question:

select t.*
from table t join
     (select trackid, min(case when actid = 21 then id end) as id21,
             min(case when actid = 5 then id end) as id5
      from table t
      group by trackid
     ) tlim
     on t.id > tlim.id21 and t.id < tlim.id5
order by id;

This find the minimum id for each trackid where the actid is 21 and 5 and chooses the rows in-between.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top