I am trying to write a query to understand whether we have a purchase price variation from the latest invoice to the second latest invoice. I am having a problem gaining the information for the second purchase invoice as SAP Query generator seems to state that The sub query for the second to last invoice is bringing through more than 1 value. Could someone give me some help on how to do this better.
SELECT DISTINCT T0.[ItemCode], T0.[Dscription],
(Select Top 1 T2.[Price] FROM PCH1 T2 WHERE T2.[ItemCOde]=T0.[ItemCode] ORDER BY T2.DocDate) AS " LAST PURCHASE PRICE",
(Select Top 1 T2.[DocDate] FROM PCH1 T2 WHERE T2.[ItemCode]=T0.[ItemCode] ORDER BY T2.DocDate) AS " LAST DATE PURCHASE PRICE",
(select Top 1(Select Top 2 T3.[Price] FROM PCH1 T3 WHERE T3.[ItemCode]=T0.[ItemCode] ORDER BY T3.DocDate) ) AS " 2nd LAST PURCHASE PRICE"
FROM PCH1 T0 INNER JOIN OITM T1 ON T0.ItemCode = T1.ItemCode
WHERE T1.[PrcrmntMtd] ='b'
ORDER BY T0.[ItemCode]
Hi Stephen Johnson...
Try this
/* Purchase price change */
declare @price dec(19,6)
declare @prprice dec(19,6)
declare @dat datetime
declare @prdat datetime
declare @item char(20)
declare @pritem char(20)
Create Table #w
(dat datetime,mind datetime,maxd datetime,
item char(20),Name char(100),pr dec(19,6))
Insert into #W
SELECT T0.[DocDate],T0.[DocDate],T0.[DocDate],
T1.[ItemCode],T1.Dscription,
T1.[Price]
FROM OPCH T0 INNER JOIN PCH1 T1 ON T0.DocEntry = T1.DocEntry
Where T0.DocType='I' --and T1.[Itemcode]='[%0]'
ORDER BY T1.[ItemCode], T0.[DocDate],T1.[Price]
Declare cu cursor for
Select item,dat,pr from #W
for update
Open cu
Fetch next from cu into @pritem,@prdat,@prprice
Fetch next from cu into @item,@dat,@price
While @@FETCH_STATUS = 0
Begin
If @pritem=@item and @prprice=@price
Update #W
set mind=@Prdat
where current of cu
else
begin set @Pritem=@item
set @prdat=@dat
set @Prprice=@price
end
Fetch next from cu into @item,@dat,@price
End
deallocate cu
select item Item,min(Name), pr Price,mind 'From',max(maxd) 'To'
from #w
group by item,mind,pr
drop table #w
Regards
Kennedy
Hi,
Try this :
SELECT DISTINCT T0.[ItemCode], T0.[Dscription],
(Select Top 1 T2.[Price] FROM PCH1 T2 WHERE T2.[ItemCOde]=T0.[ItemCode] ORDER BY T2.DocDate) AS " LAST PURCHASE PRICE",
(Select Top 1 T2.[DocDate] FROM PCH1 T2 WHERE T2.[ItemCode]=T0.[ItemCode] ORDER BY T2.DocDate) AS " LAST DATE PURCHASE PRICE",
(select Top 1 TA.[PRICE] FROM (Select Top 2 T3.[Price] FROM PCH1 T3 WHERE T3.[ItemCode]=T0.[ItemCode] ORDER BY T3.DocDate) TA ) AS " 2nd LAST PURCHASE PRICE"
FROM PCH1 T0 INNER JOIN OITM T1 ON T0.ItemCode = T1.ItemCode
WHERE T1.[PrcrmntMtd] ='b'
ORDER BY T0.[ItemCode]
Thanks & Regards,
Nagarajan
Add a comment