我在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
答案 0 :(得分:5)
select ID, Name
FROM (select ID, Name, -- add other columns here
ROW_NUMBER() over (partition by Name ORDER BY ID DESC) as MAX_ID
from Customer) x
WHERE MAX_ID = 1