I have the following query (built to showcase the problem)
WITH
CategoryPromotions
AS
(
SELECT CategoryId = 7, Price = 10
UNION ALL
SELECT CategoryId = 3, Price = 15
UNION ALL
SELECT CategoryId = 1, Price = 5
)
,
Products
AS
(
SELECT Id = 1, Price = 20
)
,
ProductsCategories
AS
(
SELECT ProductId = 1, CategoryId = 2
UNION ALL
SELECT ProductId = 1, CategoryId = 8
UNION ALL
SELECT ProductId = 1, CategoryId = 6
)
,
Tally
AS
(
SELECT N = 1
UNION ALL
SELECT N = 2
UNION ALL
SELECT N = 3
UNION ALL
SELECT N = 4
UNION ALL
SELECT N = 5
)
,
Hierarchy
AS
(
SELECT Id = 2, SortPath = 0x00000001000000070000000400000002
UNION ALL
SELECT Id = 8, SortPath = 0x00000001000000070000000400000008
UNION ALL
SELECT Id = 6, SortPath = 0x0000000300000006
)
SELECT ProductsCategories.*, xD.*
FROM Products
RIGHT JOIN ProductsCategories
ON Products.Id = ProductsCategories.ProductId
CROSS APPLY
(
SELECT TOP (1) promos.CategoryId
, Products.Price AS BasePrice
, promos.Price
, (
CASE
WHEN promos.Price IS NOT NULL THEN
(Products.Price - promos.Price)
ELSE
Products.Price
END
) AS DiscountedPrice
, ROW_NUMBER() OVER
(
ORDER BY CASE
WHEN promos.Price IS NOT NULL THEN
(Products.Price - promos.Price)
ELSE
Products.Price
END
ASC
) AS PriceRank
FROM (SELECT ProductsCategories.ProductId, ProductsCategories.CategoryId) bpc
CROSS APPLY
(
SELECT TOP (1) categories.CategoryId
, catpromo.Price
FROM
(
SELECT CategoryId = CAST(SUBSTRING(Hierarchy.SortPath,Tally.N,4) AS INT)
, Tally.N
FROM Hierarchy
INNER JOIN Tally
ON Tally.N BETWEEN 1
AND DATALENGTH(Hierarchy.SortPath)
WHERE Hierarchy.Id = bpc.CategoryId
GROUP BY SUBSTRING(Hierarchy.SortPath,tally.N,4)
, tally.n
) AS categories
INNER JOIN CategoryPromotions catpromo
ON categories.CategoryId = catpromo.CategoryId
ORDER BY categories.N DESC
) AS promos
WHERE bpc.ProductId = 1
ORDER BY PriceRank
) AS XD
WHERE products.Id = 1;
This is the query result:
Why the ROW_NUMBER isn't working? And is there anything I can do in order to improve the query performance? This will be applied to a million row result query for each individual product. I tried to fake +/- the structure that it will be used in.
The desired result is the 1 row that has the lowest DiscountedPrice. (Cannot use MIN, since I need all the columns)
EDIT: Without TOP (1)