LINQ查询查找一列的最小值
我有一个包含以下列的表,
inspection_dt,
contact_dt,
description,
product_mod,
product_desc,
contact_nm,
history_id,
inspect_id,
history_type,
incident_product_id,
contact_history_id
我将使用 LINQ 查询该表中的通用行列表。不同之处在于我想要history_id 的最小(MIN) 值——并模仿这个SQL 查询。
SELECT DISTINCT
inspection_dt,
contact_dt,
description,
product_mod,
product_desc,
contact_nm,
MIN(history_id) AS history_id,
inspect_id,
history_type,
incident_product_id,
contact_history_id
FROM
myTable
GROUP BY
inspection_dt,
contact_dt,
description,
product_mod,
product_desc,
contact_nm,
inspect_id,
history_type,
incident_product_id,
contact_history_id
我已经尝试过类似的片段
var searchData = items
.GroupBy(i => new { i.history_id })
.Select(g => new { history = g.Min() })
.Distinct();
,但仍然一团糟,
我在使用 MIN、MAX 等函数时遇到困难,并在 LINQ 中进行分组,并且非常感谢我能得到的任何帮助。
谢谢,
I have a table with the following columns
inspection_dt,
contact_dt,
description,
product_mod,
product_desc,
contact_nm,
history_id,
inspect_id,
history_type,
incident_product_id,
contact_history_id
I would to use LINQ to query a generic list of rows from this table. The twist is that I want the smallest (MIN) value of history_id -- and mimic this SQL query.
SELECT DISTINCT
inspection_dt,
contact_dt,
description,
product_mod,
product_desc,
contact_nm,
MIN(history_id) AS history_id,
inspect_id,
history_type,
incident_product_id,
contact_history_id
FROM
myTable
GROUP BY
inspection_dt,
contact_dt,
description,
product_mod,
product_desc,
contact_nm,
inspect_id,
history_type,
incident_product_id,
contact_history_id
I've tried snippets like
var searchData = items
.GroupBy(i => new { i.history_id })
.Select(g => new { history = g.Min() })
.Distinct();
But still get all messed up
I get stuck using functions like MIN, MAX, etc, and grouping in LINQ and would appreciate any help I can get.
Thanks,
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果要完全模拟查询,则需要按 SQL 中分组所依据的相同列或字段进行分组。尝试类似的东西
If you want to mimic the query completely, you need to group by the same columns or fields you're grouping by in your SQL. Try something like
您可以尝试下面的代码。
我注意到当我在探查器中查看它时它会生成一个 SQL 交叉连接,但我认为它可以满足您的需求,并且您可能可以对其进行更多调整。
希望这有帮助
You could try this code below.
I noticed it generates an SQL cross join when i view it in profiler but i think it does what you want and you might be able to tweak it more.
Hope this helps