![](/img/trans.png)
[英]SQL SELECT only rows where a max value is present, and the corresponding ID from another linked table
[英]select rows from table where id=max
我有几行具有相同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
您可以使用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;
实体框架建议您使用SQL Server。 然后,您可以使用我最喜欢的方法,该方法不使用子查询:
select top (1) with ties t.*
from t
order by row_number() over (partition by processid order by id desc);
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();
通过 max(id)进行简单分组的方式如何
select max(id), processID, message, status
from TableFoo
group by processID
它应该携带消息,状态为max(id)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.