I am trying to select 4 Columns from temp tables I have created, I am struggling to get one of the columns to display its data.
I have written the statement differently to try and get the correct data however an Union is needed in order to subtract the Quantity from second table
Create table #temp110
(
ItemCode nvarchar(50),
[Quantity 6 months ago] int
)
Create table #temp6to12
(
ItemCode nvarchar(50),
[Quantity 6 to 12 Months Ago] int
)
GO
select top 20
oi.[Itemcode],
sum(qu.[Quantity]) as [Quantity 6 months ago]
into #temp110
from miro.dbo.oitm oi
join miro.dbo.qut1 qu on oi.ItemCode = qu.ItemCode
WHERE DATEDIFF( MONTH, qu.docdate, GETDATE()) < 64
group by oi.[Itemcode], qu.Quantity
order by qu.quantity DESC
-- qty of itms between 6 & 12 months back, lowest 10 !!All Items
select top 20
oi.[Itemcode],
sum(qu.[Quantity]) as [Quantity 6 to 12 Months Ago]
into #temp6to12
from miro.dbo.oitm oi
join miro.dbo.qut1 qu on oi.ItemCode = qu.ItemCode
WHERE DATEDIFF( MONTH, qu.docdate, GETDATE()) > 6
and DATEDIFF( MONTH, qu.docdate, GETDATE()) < 12
group by oi.[Itemcode], qu.Quantity
order by qu.quantity DESC
SELECT
UN.ItemCode,
UN.[Quantity 6 To 12 Months Ago],
UN.[Quantity Differance]
FROM(
select
t1.Itemcode,
t1.[Quantity 6 to 12 Months Ago],
t1.[Quantity 6 To 12 Months Ago] as [Quantity Differance]
from #temp6to12 t1
join #temp110 t2 on t1.[ItemCode] = t2.[ItemCode]
UNION
select
t2.Itemcode,
t2.[Quantity 6 months ago],
- t2.[Quantity 6 Months Ago] as [Quantity Differance]
from #temp110 t1
join #temp110 t2 on t1.[ItemCode] = t2.[ItemCode]
) as Un
order by un.[Quantity Differance] ASC
Currently This code works and however it does not display a value for [Quantity 6 months ago], Which is what I ultimately need.
If I try to call it from the Union as I have with [Quantity 6 to 12 Months Ago] It does not pick it up, I suspect this is because [Quantity 6 to 12 Months Ago] is used to subtract from [Quantity 6 months ago] in the Union. The fact that it is used mathematically mean I cannot call it from the Union?
Expect to be able to add UN.[Quantity 6 months ago] to the select statement