SELECT
CategoryId,
MAX(CASE WHEN MaxRN = 1 THEN ItemId ELSE NULL END) IdMaxValue,
MAX(CASE WHEN MinRN = 1 THEN ItemId ELSE NULL END) IdMinValue
(
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
) as DerivedTable
WHERE MaxRN = 1 or MinRN = 1
GROUP BY CategoryId
</code>