SELECT s.id, s.date, pr.price, t.descc, s.qty, s.qty * pr.price
FROM sales s
OUTER APPLY (
SELECT TOP (1) price
FROM prices p
WHERE p.id = s.id AND p.date <= s.date
ORDER BY p.date DESC
) AS pr
INNER JOIN type t ON t.id = s.id
;WITH pricecte AS
(
SELECT id, updatedate as fromdate, price, row_number() over(PARTITION BY id ORDER BY dbo.price.updatedate ASC ) rno
from price
), pricectemaster AS (
SELECT p.id, p.price, p.fromdate, dateadd(dd,-1,p2.fromdate) todate
FROM pricecte p
LEFT OUTER JOIN pricecte p2
ON p.id= p2.id
AND p.rno +1 = p2.rno )
SELECT s.id, s.date, p.price, t.descc, s.qty, s.qty * p.price AS total
FROM sales s
INNER JOIN pricectemaster p
on p.id = s.id
AND s.date BETWEEN p.fromdate and isnull(p.todate , s.date)
INNER JOIN type t
ON t.id = s.id
Curious why you would not want to use OUTER APPLY? I've found it a very efficient approach to this type of problem (unless you are on a very old version of SQL )
Select * from
(Select B.,A.SoldDate,A.Qty,C.PriceDate,A.QtyC.Price Total,
ROW_NUMBER() Over (Partition By A.Id,SoldDate Order By PriceDate Desc) RowNo
from Sales A
Inner join Product B On B.Id = A.Id
Inner join Price C On C.Id = A.Id And A.SoldDate>=C.PriceDate) Tbl
Where Tbl.RowNo = 1
SELECT s.id, s.date, p.price, t.descc, s.qty, s.qty * p.price AS total
FROM sales s
INNER JOIN pricectemaster p
on p.id = s.id
AND s.date BETWEEN p.fromdate and isnull(p.todate , s.date)
INNER JOIN type t
ON t.id = s.id
What is wrong in this output?
as per your sample output last line is differ because there is no rows to retrieve 2015-03-21 in sales table. Please explain
SELECT s.id, s.date, p.price, t.descc, s.qty, s.qty * p.price AS total
FROM sales s
INNER JOIN pricectemaster p
on p.id = s.id
AND s.date BETWEEN p.fromdate and isnull(p.todate , s.date)
INNER JOIN type t
ON t.id = s.id