简体   繁体   中英

c# - Group by and having with two counts in Linq

How can I write the follow query with Linq in C#?

SELECT MAX(A2.LINHA_PLANILHA)
FROM MD_IMP_FORCA_VENDA_DADOS_A2 A2
WHERE A2.LINHA <> '0' 
    AND TRIM(A2.SETORES) IS NOT NULL
    AND A2.LINHA_PLANILHA <> 1
    AND USUARIO = V_USUARIO
GROUP BY A2.LINHA, A2.BRICK
HAVING COUNT(A2.BRICK) > 1 AND COUNT(DISTINCT A2.SETORES) > 1;

I thought to do this:

var result = from r in dataTable.AsEnumerable() 
where r.Field<string>(1) != "0" 
    && r.Field<string>(2).Trim() != null 
    && r.Field<Int32>(0) != 1 
group r by new {Linha = r.Field<string>(1), Brick = r.Field<string>(3) } into temp 
where temp.Count() > 1 
select new { MaxLinha = (from r2 in temp select r2.Field<Int32>(0)).Max()}; 

But I don't know how to put the two COUNTS of HAVING clause in Linq query.

Any help would be appreciated.

Thanks

Zago

Perhaps:

var query = db.MD_IMP_FORCA_VENDA_DADOS_A2
    .Where(x => x.LINHA  != "0" 
             && x.SETORES != null 
             && x.SETORES.Trim() != ""
             && x.LINHA_PLANILHA <> 1
             && x.USUARIO = x.V_USUARIO
    ) 
    .GroupBy(x => new { x.LINHA, x.BRICK })
    .Where(g => g.Count() > 1 && g.Select(x => x.SETORES).Distinct().Count() > 1)
    .Select(g => g.Max(x => x.LINHA_PLANILHA));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM