Linq查询使用group by和having

Lui*_*eri 6 c# linq sql-server

所以,我一直在尝试复制这个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
Run Code Online (Sandbox Code Playgroud)

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();
Run Code Online (Sandbox Code Playgroud)

但是,我知道它应该是正确的,因为我没有在我的组子句中选择大于1的实际计数.

如何将此SQL查询作为LINQ查询来完成?

das*_*ght 8

LINQ Where和之间没有区别Having.将根据您的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
Run Code Online (Sandbox Code Playgroud)


oct*_*ccl 7

更改Key.ActionId.Count()wheregroup by:

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