Linq查询使用group by和having

时间:2015-11-25 15:55:46

标签: c# sql-server linq

所以,我一直在尝试复制这个SQL查询:

select COUNT(*) as Total_2_Review
from (
    select processed_image_id, count(*) as Total_Confirm from dbo.history 
    where action_id=104
    group by processed_image_id
    having count(*) > 1
) as tbl

Linq如下:

var total2Review = (from h in secondDb.Histories.Where(i => i.ActionId == 104)
                    group h by new { h.ActionId, h.ProcessedImageId } into g
                    where g.Key.ActionId > 1
                    select g).Count();

但是,我知道这不应该是正确的,因为我没有在我的小组条款中选择大于1的实际小数。

如何以LINQ查询完成此SQL查询?

2 个答案:

答案 0 :(得分:8)

LINQ在WhereHaving之间没有区别。将根据您Where子句的位置生成适当的SQL查询。

以下是我将SQL查询转换为LINQ的方法:

var total2Review = secondDb.Histories
    .Where(i => i.ActionId == 104) // This "Where" remains a "where"
    .GroupBy(i => i.ProcessedImageId)
    .Where(g => g.Count() > 1)     // This "Where" becomes "having"
    .Count();                      // This gets the overall count

答案 1 :(得分:7)

Key.ActionId后的.Count()中更改where的{​​{1}}:

group by