I wrote a query to extract the most recent price of products and what that price was from tables in our company's SQL Server database and used UNION
to join it with the most recent delivery price for those same products. Is there a way I can now nest that union query into another one to find the newest price from the unionised table?
This is the code of the working union query:
select LastCostDate,
[LocStock].SiteID,
[LastDate].PLUID,
[LastDate].Description,
[LastCost].Cost
From (select max([PLUCostHistory].ChangeDate) as LastCostDate, [PLUCostHistory].PLUID, [PLU].Description From [PLUCostHistory] Inner Join [PLU]
on [PLU].PLUID=[PLUCostHistory].PLUID group by [PLUCostHistory].PLUID, [PLU].Description ) as LastDate
Inner Join (select [PLUCostHistory].ChangeDate, [PLUCostHistory].PLUID, [PLU].Description, sum([PLUCostHistory].Cost) as Cost From [PLUCostHistory] Inner Join [PLU]
on [PLU].PLUID=[PLUCostHistory].PLUID group by [PLUCostHistory].ChangeDate, [PLUCostHistory].PLUID, [PLU].Description ) as LastCost
On LastDate.Description=LastCost.Description
And LastDate.LastCostDate=LastCost.ChangeDate
And LastDate.PLUID=LastCost.PLUID
Inner Join [LocStock]
on [LocStock].PLUID=[LastDate].PLUID
UNION
select LastCostDate,
[DelMast].SiteID,
[LastDate].PLUID,
[LastDate].Description,
[LastCost].Cost
From (select max([DelMast].DeliveryDate) as LastCostDate, [DelDets].PLUID, [PLU].Description From [DelMast] Inner Join [DelDets]
on [DelDets].DeliveryID=[DelMast].DeliveryID Inner Join [PLU] on [PLU].PLUID=[DelDets].PLUID Inner Join [PLUGroupRef]
on [DelDets].PLUID=[PLUGroupRef].PLUID Inner Join [PLUGroup2]
on [PLUGroup2].PLUGroup2ID=[PLUGroupRef].PLUGroup2ID group by [DelDets].PLUID, [PLU].Description) as LastDate
Inner Join (select [DelMast].DeliveryDate, [DelDets].PLUID, [PLU].Description, sum([DelDets].Cost) as Cost From [DelMast] Inner Join [DelDets] on [DelDets].DeliveryID=[DelMast].DeliveryID Inner Join [PLU]
on [PLU].PLUID=[DelDets].PLUID group by [DelMast].DeliveryDate, [DelDets].PLUID, [PLU].Description) as LastCost
On LastDate.Description=LastCost.Description
And LastDate.LastCostDate=LastCost.DeliveryDate
And LastDate.PLUID=LastCost.PLUID
Inner Join [LocStock]
on [LocStock].PLUID=[LastDate].PLUID
Inner Join [DelMast]
on [LocStock].SiteID=[DelMast].SiteID
Table 1
ChangeDate | Product | Cost |
---|---|---|
01/01/2000 | Water | 5 |
06/01/2000 | Banana | 2 |
09/01/2000 | orange | 3 |
10/01/2000 | Water | 3 |
01/01/2000 | Banana | 2.5 |
Table 2
ChangeDate | Product | Cost |
---|---|---|
08/01/2000 | Water | 6 |
03/01/2000 | Banana | 1 |
05/01/2000 | Water | 3 |
02/01/2000 | Banana | 3 |
12/01/2000 | orange | 4 |
Desired output:
ChangeDate | Product | Cost |
---|---|---|
10/01/2000 | Water | 3 |
06/01/2000 | Banana | 2 |
12/01/2000 | orange | 4 |