WITH CTE AS
(
SELECT
*,
ROW_NUMBER() OVER(PARTITION BY CategoryId ORDER BY ItemValue DESC) MaxRN,
ROW_NUMBER() OVER(PARTITION BY CategoryId ORDER BY ItemValue ASC) MinRN
FROM Items
)
SELECT
CategoryId,
MIN(CASE WHEN MaxRN = 1 THEN ItemId END) IdMaxValue,
MIN(CASE WHEN MinRN = 1 THEN ItemId END) IdMinValue
FROM CTE
GROUP BY CategoryId