从表中选择id = max的行

时间:2018-05-13 05:54:51

标签: sql entity-framework

我的表格中有多个行具有相同的ProcessID但不同的ID。如何在SQL查询和实体框架中选择最大ID和不同ProcessID的行?

我的表:

ID     | ProcessID  | MESSAGE    | STATUS
-------+------------+------------+--------
100    | 100        | test       | 2
101    | 100        | test       | 2
102    | 100        | test       | 3
103    | 100        | test       | 4
104    | 104        | test       | 5
105    | 104        | test       | 6
106    | 104        | test       | 7
107    | 104        | test       | 8
108    | 104        | test       | 09

搜索时:

ID     | ProcessID  | MESSAGE    | STATUS
-------+------------+------------+---------    
103    | 100        | test       | 4
108    | 104        | test       | 09

4 个答案:

答案 0 :(得分:1)

您可以使用ROW_NUMBER

SELECT  ID, ProccessID, MESSAGE, STATUS 
FROM (SELECT *, 
         ROW_NUMBER() OVER(PARTITION BY ProcessID ORDER BY id DESC) AS rn
      FROM tab) sub
WHERE rn = 1;

答案 1 :(得分:0)

实体框架建议您使用SQL Server。然后你可以使用我最喜欢的方法,它不使用子查询:

select top (1) with ties t.*
from t
order by row_number() over (partition by processid order by id desc);

答案 2 :(得分:0)

var data = (from item in ctx.Processes
            group item by item.ProcessID into sub
            let maxId = sub.Max(x => x.ID)
            select new
            {
                ID = maxId,
                ProcessID = sub.Key,
                sub.Where(x => x.ID == maxId).First().MESSAGE,
                sub.Where(x => x.ID == maxId).First().STATUS
            }).ToList();

//or this variant
data = (from item in ctx.Processes
        join gr in (from temp in ctx.Processes
                    group temp by temp.ProcessID into sub
                    select sub.Max(x => x.ID))
        on item.ID equals gr
        select new
        {
            item.ID,
            item.ProcessID,
            item.MESSAGE,
            item.STATUS,
        }).ToList();

答案 3 :(得分:0)

一个简单的分组如何使用max(id)

select max(id), processID, message, status   
from TableFoo  
group by processID

它应该带有消息,状态为max(id)