0

I have the following raw query:

select * 
from (select * from settings order by priority desc) x
group by name

I would like to use a laravel 5 query builder instead but cant get the subquery to work. Is there a way to do this without using raw query's?

The table:

id - name - priority
1    1      1
2    1      2
3    2      1

In the above case It will return row 2 and 3 like I want to

I tried this query:

$settings = \App\Setting::where('user_id', Auth::id())->orWhere('tool_id', $id)->groupBy('name')->orderBy('priority', 'desc')->get();

But this will return row 1 and 3.

Merijndk
  • 1,674
  • 3
  • 18
  • 35

1 Answers1

1

Can you use CTE expressions? RANK() would work:

WITH CTE AS
(
  SELECT *, RANK() OVER(PARTITION BY name ORDER BY priority desc) AS RowRank 
  FROM settings
)
SELECT id, name, priority
FROM CTE c
WHERE c.RowRank = 1
Regolith
  • 2,944
  • 9
  • 33
  • 50
Sergio
  • 503
  • 3
  • 11