Sql-server – SELECT highest quantity in related table, exclude if there is a tie

sql serversql-server-2005

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:

SELECT qty.Id 
     , qty.Product_Name
     , qty.Product_Type
FROM (
    SELECT qty.Id 
     , qty.Product_Name
     , qty.Product_Type
     , COUNT(Rnk) OVER () as cnt
    FROM ( 
        SELECT td.Id, prd.Product_Name, prd.Product_Type
        ,  RANK() OVER (PARTITION BY prd.Receipt_Number 
                        ORDER BY prd.Quantity) AS Rnk
        FROM Transactions td
        JOIN Products prd
            ON prd.Receipt_Number = td.Receipt_Number
        WHERE prd.Quantity > 1 
    ) qty
    WHERE qty.Rnk = 1
) WHERE cnt = 1;

If you want the rows, but with null instead of values you can use a case expression:

SELECT CASE WHEN cnt = 1 THEN qty.Id END 
     , CASE WHEN ... qty.Product_Name ...
     , ...
FROM (
...
);