我在 SQL Server 中有表。我想在每个组中找到最后一行。我尝试了以下查询,但它没有返回确切的结果。ID 列是 PK,其他列设置为 NOT NULL。
select ID, Name FROM
(select ID, Name, max(ID) over (partition by Name) as MAX_ID
from Customer) x where ID= MAX_ID
要更清楚。我有 2 个查询。首先:
ALTER PROCEDURE [dbo].[Ramiz_Musterija_RowNum]
@Datum DATE,
@BrojKamiona INT
AS SET NOCOUNT ON
SELECT Ime,MusterijaID,RowNum=ROW_NUMBER() OVER(ORDER BY Ime)FROM Musterije
WHERE Datum=@Datum AND BrojKamiona=@BrojKamiona GROUP BY Ime,MusterijaID
第二个:
ALTER PROCEDURE [dbo].[Ramiz_Musterija_FindLast]
@Datum DATE,
@BrojKamiona INT
AS SET NOCOUNT ON
SELECT a.* from Musterije a
JOIN (SELECT Ime, MAX(MusterijaID) AS MAXID FROM Musterije GROUP BY Ime) AS b
ON a.MusterijaID = b.MAXID AND a.Datum=@Datum AND a.BrojKamiona=@BrojKamiona
然后 LINQ 查询:
var rowNumList = from f in customerFindLastList
join r in customerRowNumList
on f.MusterijaID equals r.MusterijaID
select new { r.RowNum };
我试图在每一行中找到最后一行,然后在 MusterijaID 列上匹配这两个查询。对此的任何帮助将不胜感激。这是一组的输出。现在,问题是这两个查询在“4250” MusterijaID 上匹配,但我需要在“4229”上匹配查询。
Ime MusterijaID
100//1 4246
100//1 4247
100//1 4248
100//1 4249
100//1 4250
100//1 4229