Groupwise Max Multiple Columns

268 Views Asked by At

Ive written a query that allows me to get the closest rooms using the groupwise max method. But how do I do groupwise max for multiple columns?

I have the query below where the subquery gives me the closest rooms and then joins them with the main table. Now I want to pick the first event that will happen next.

Ex: MIN(DATEDIFF( date, now())) > 0

SELECT name, date, t1.Room, descr, t1.D
FROM Events
JOIN
(
        SELECT Roomid, Room, Latitude, Longitude,
                ACOS(SIN((:lat))*SIN(RADIANS(Latitude)) + COS((:lat))*COS(RADIANS(Latitude))*COS(RADIANS(Longitude)-(:lon)))*(:R) AS D
        FROM Rooms
        WHERE Latitude>(:minLat) AND Latitude<(:maxLat)
                AND Longitude>(:minLon) AND Longitude<(:maxLon)
                AND ACOS(SIN((:lat))*SIN(RADIANS(Latitude)) + COS((:lat))*COS(RADIANS(Latitude))*COS(RADIANS(Longitude)-(:lon)))*(:R) < (:rad)
) AS t1 ON Events.roomid = t1.Roomid
GROUP BY Room
ORDER BY D

Can someone give me any pointers on how to do this?

Thanks!

P.S: The event should be the next occurring event. I don't use ABS(MIN()) because that will return events that already happened.

1

There are 1 best solutions below

4
Matt Dodge On

Assuming D is your date, order by date difference and limit 1

SELECT name, date, t1.Room, descr, t1.D
FROM Events
JOIN
(
        SELECT Roomid, Room, Latitude, Longitude,
            ACOS(SIN((:lat))*SIN(RADIANS(Latitude)) + COS((:lat))*COS(RADIANS(Latitude))*COS(RADIANS(Longitude)-(:lon)))*(:R) AS D
    FROM Rooms
    WHERE Latitude>(:minLat) AND Latitude<(:maxLat)
            AND Longitude>(:minLon) AND Longitude<(:maxLon)
            AND ACOS(SIN((:lat))*SIN(RADIANS(Latitude)) + COS((:lat))*COS(RADIANS(Latitude))*COS(RADIANS(Longitude)-(:lon)))*(:R) < (:rad)
) AS t1 ON Events.roomid = t1.Roomid
ORDER BY DATEDIFF( D, now())
LIMIT 1