I have a JSON which contains an array of payments done to different employees.
We need to write a query to find the highest 2 payments(and its details) done to each employee.
What would be an appropriate n1ql query ?
If you need per employee basis across the documents, Unnest array, group by name and then do sub query expressions.
SELECT d1.name, (SELECT p.* FROM d1.np AS p ORDER BY p.payment DESC LIMIT 2) AS payments
FROM (SELECT du.name, ARRAY_AGG(du) AS np
FROM default AS d UNNEST d.payments AS du
GROUP BY du.name) AS d1;
Same query as above but the expected output you want (removes extra layers of objects)
SELECT RAW (SELECT RAW p FROM d1 AS p ORDER BY p.payment DESC LIMIT 2)
FROM ( SELECT RAW ARRAY_AGG(du)
FROM default AS d
UNNEST d.payments AS du
GROUP BY du.name) AS d1;