This question already has answers here:
Get top 1 row of each group (19 answers)
Closed yesterday.
Ok, I'm not very good with SQL, so I don't know how to solve this one. I have this query:
DECLARE @supplyPointIds TABLE
(
id UNIQUEIDENTIFIER
)
INSERT INTO @supplyPointIds (id)
VALUES ('1DC9A405-4EC5-4379-BB2C-110973A9936B'),
('65745684-7D00-4D8A-9735-2C5BA29852B0')
SELECT R.Id AS LastReadingId, R.SupplyPointInstallationId
FROM Reading R
WHERE R.SupplyPointInstallationId IN (SELECT id FROM @supplyPointIds)
ORDER BY R.SupplyPointInstallationId, R.LastDate DESC
And it produces this:
But what I want to get is this only:
So, I wrote this query:
DECLARE @supplyPointIds TABLE
(
id UNIQUEIDENTIFIER
)
INSERT INTO @supplyPointIds (id)
VALUES ('1DC9A405-4EC5-4379-BB2C-110973A9936B'),
('65745684-7D00-4D8A-9735-2C5BA29852B0')
SELECT ReadingId.Id AS LastReadingId, R.SupplyPointInstallationId
FROM Reading R,
(SELECT TOP 1 RID.Id
FROM Reading RID
WHERE RID.SupplyPointInstallationId = R.SupplyPointInstallationId
ORDER BY RID.LastDate) AS ReadingId -- Only the most recent reading
WHERE R.SupplyPointInstallationId IN (SELECT id FROM @supplyPointIds)
ORDER BY R.SupplyPointInstallationId DESC
But, unfortunately, I get this error:
The multi-part identifier "R.SupplyPointInstallationId" could not be bound.
How can I do to get only those two records I want?
1条答案
按热度按时间0yg35tkg1#
Try to join the two tables and use the row_number function as the following:
See demo
This can be also written as: