Sort by IP address, then keep the selection of entries until I have 3 unique IP addresses

I probably probably thought about that completely.

I have a report table in my database that has an IP column (varchar), Data-column (INT) and Timestamp-column (TIMESTAMP).

I need to write a query in which I sort by Timestamp DESC, and then basically keep the selection of records at the top, until my result set contains at least 3 unique IP addresses in the order they occur until the 4th IP address appears.

For example:

IP         Data         Timestamp
1.1.1.0    0            1-1-2016
1.1.1.1    1            1-2-2016
1.1.1.1    2            1-3-2016
1.1.1.2    1            1-4-2016
1.1.1.3    1            1-5-2016
1.1.1.3    1            1-6-2016

In this case, I want to get a result set:

IP         Data         Timestamp
1.1.1.3    1            1-6-2016
1.1.1.3    1            1-5-2016
1.1.1.2    1            1-4-2016
1.1.1.1    2            1-3-2016
1.1.1.1    1            1-2-2016

For precedent only: Using this data, the backend will group IP addresses, generate the average value of the data column (basically smoothing 1+ IP to 1) before processing it further.

GROUP BY, HAVING, Sub-query, , !

EDIT:

SELECT DISTINCT ip
FROM report
ORDER BY timestamp DESC
LIMIT 3

IP. , 1.1.1.3 , DISTINCT IP-, , ( , LIMIT 3).

:

SELECT *
FROM report
WHERE ip in (
    SELECT DISTINCT ip
    FROM report
    ORDER BY timestamp DESC
)
ORDER BY timestamp DESC
LIMIT 3

, , , ... LIMIT IN, MySQL . LIMIT, , , .

+4
2

- , :

SELECT * 
FROM report
WHERE Timestamp >= (
    SELECT MIN(Timestamp) FROM (
        SELECT IP, MIN(Timestamp) as Timestamp
        FROM report
        GROUP BY IP
        ORDER BY Timestamp DESC
        LIMIT 3
    ) x
)
ORDER BY Timestamp DESC

, , .

SQL Fiddle, .

+3

SELECT AVG(data), ip 
GROUP BY ip 
ORDER BY timestamp DESC
LIMIT 0,3

. X ips, , .

+1

Source: https://habr.com/ru/post/1627573/


All Articles