簡體   English   中英

Linq查詢使用group by和having

[英]Linq query using group by and having

所以,我一直在嘗試復制這個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的實際計數。

如何將此SQL查詢作為LINQ查詢來完成?

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

group by之后的where更改Key.ActionId .Count()

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();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM