puiu91
4/21/2016 - 1:18 PM

SQL one to many using rank

SQL one to many using rank

$ids = array_column($houses, 'houseId');
$ids = array_filter($ids); // remove empty array place holders
$ids = array_values($ids); // reset array key index
$ids = FormatSQL::whereIn($ids); // prepare for use with a WHERE IN() clause

$query = <<<SQL

    WITH CTE AS(
        SELECT houses.id  AS 'houseId'
             , houses.price AS 'price'
             , RANK() OVER (PARTITION BY houses.id ORDER BY houses.dateListed DESC) AS 'rank'
        FROM  houses
        WHERE houseId.id IN ( $ids )
    )
    SELECT houseId, price FROM CTE WHERE rank = 1

SQL;