I have the following query that throws a result like in the example:
SELECT P.IdArt, P.IdAdr, P.gDate, P.Price
FROM dbo.T_PriceData AS P INNER JOIN
dbo.T_Adr AS A ON P.IdAdr = A.IdAdr INNER JOIN
dbo.T_Stat AS S ON A.IdStat = S.IdStat
GROUP BY P.IdArt, P.IdAdr, P.gDate, P.Price
IdArt IdAdr gDate Price
1 10 01/01/2018 1.25
1 10 02/01/2018 1.17
1 10 03/01/2018 1.18
2 15 01/01/2018 1.03
2 18 10/01/2018 0.12
3 25 12/01/2018 0.98
3 25 28/01/2018 1.99
4 30 15/01/2018 2.55
5 35 08/01/2018 0.11
The final result I want is:
- When the IdArt and IdAdr are the same, there should be only one row with the highest date of all rows (CASE IdArt 1)
- When IdArt is the same but IdAdr is different, there should be a row with each IdAdr with the highest date for each IdAdr. (CASE IdArt 2)
- Price doens't affect anything.
So the final table I would like to have is:
IdArt IdAdr gDate Price
1 10 03/01/2018 1.18
2 15 01/01/2018 1.03
2 18 10/01/2018 0.12
3 25 28/01/2018 1.99
4 30 15/01/2018 2.55
5 35 08/01/2018 0.11
How can I do that? I tried with a having clausule selecting by MAX(gDate) but, of course, I only get one row with the max date from the whole database.
MAX(gDate), MAX(Price) ... GROUP BY IdArt, IdAdr() IN ();INNER JOIN max_table; ....MAX(price)should not work.MAXwould return the wrong values; such as the price1.25for the date03/01/2018onID1.