I have a SELECT statement that pulls in product information from a related table, and finds the product with the highest quantity associated to it for that transaction. This is shown below and working as expected:
SELECT
qty.[Id],
qty.[Product_Name],
qty.[Product_Type]
FROM
( SELECT td.[Id], prd.[Product_Name], prd.[Product_Type],
ROW_NUMBER() OVER (PARTITION BY prd.Receipt_Number ORDER BY prd.Quantity DESC) AS Row
FROM [Transactions] td
INNER JOIN [Products] prd
ON prd.[Receipt_Number] = td.[Receipt_Number]
WHERE prd.Quantity > 1
) qty
WHERE
qty.Row = 1
The issue is that there may be multiple products that have the exact same quantity. Current the system will pull in the first record it finds of the multiple matches, but I would like to exclude this inner query entirely if there is a tie on the highest quantity, returning a null value. Is this possible?
Best Answer
It's a bit unclear what you want, but you can use rank() to collect duplicates, and then another window function that counts those, and filter them out if there is more than one:
If you want the rows, but with null instead of values you can use a case expression: