当数据值大于x时,我选择了如下所示的表格,将其称为事件。现在我想在事件发生之前抓取最后三次唯一(id1,id2)对在我的数据库中的数据。
example table 1 (after filtering for data>x)
id1 id2 time data
76 1234 t101 d1
46 9573 t102 d2
24 3632 t103 d3
88 4792 t104 d4
17 7799 t105 d5
74 2274 t106 d6
example output table
id1 id2 time data
76 1234 t101 d1*
76 1234 t76 d2
76 1234 t44 d3
76 1234 t32 d4
46 9573 t102 d5 *
46 9573 t99 d6
46 9573 t98 d7
46 9573 t91 d8
到目前为止,我已经考虑过id1 * id2来生成一个新的唯一id:id1_id2,可以在其上加入。得到类似"示例输出表"但是对于id1_id2的所有数据,不仅仅是事件之前的三个数据条目。
答案 0 :(得分:0)
这可能是您想要的,具体取决于说明:
SELECT numbered.*
FROM SELECT filtered.*,
IF (id12 = @prev,
@n := @n + 1,
@n := 1 AND @prev := id12) as position
FROM
(SELECT mytable.*, concat_ws('_', id1, id2) as id12
FROM (SELECT id1, id2, time FROM mytable WHERE data > x) AS mytablex
INNER JOIN mytable
ON mytable.id1 = mytablex.id1 AND mytable.id2 = mytablex.id2
ORDER BY id1, id2, time DESC)
AS filtered
JOIN (SELECT @n := 0, @prev := '') AS setup)
AS numbered
WHERE numbered.position < 4