将Agregate COUNT中的DISTINCT转换为LINQ

时间:2017-03-08 05:27:33

标签: c# sql linq distinct

我正在使用Linqer

将SQL转换为LINQ
SELECT CC.col1,CC.col2,CC.col3 FROM dbo.Table1 CC
WHERE CC.Status IN (0,3) AND CC.col4 IN (2,3,4,5)
GROUP BY CC.col1,CC.col2,CC.col3
HAVING COUNT(DISTINCT CC.Status) = 2

但显示以下错误

SQL无法转换为LINQ:Agregate中的DISTINCT COUNT无法转换为LINQ

2 个答案:

答案 0 :(得分:2)

更改sql select,如下所示:

SELECT CC.col1,CC.col2,CC.col3 FROM dbo.Table1 CC
WHERE CC.Status IN (0,3) AND CC.col4 IN (2,3,4,5)
GROUP BY CC.col1,CC.col2,CC.col3
HAVING (select  COUNT(DISTINCT CC.Status) FROM dbo.Table1 CC) = 2

Linqer 中的输出如下所示:

 from CC in db.Table1
  where
 (new int[] {0, 3 }).Contains(CC.Status) &&
 (new int[] {2, 3, 4, 5 }).Contains(CC.col4)
 group CC by new {
   CC.col1,
   CC.col2,
   CC.col3
 } into g
 where
 ((from Table1 in db.Table1
 select new {
  g.Key.Status
}).Distinct()).Count(p => g.Key.Status != null) == 2
 select new {
   g.Key.col1,
   g.Key.col2,
   g.Key.col3
}

答案 1 :(得分:1)

最终条款COUNT(DISTINCT CC.Status)中此部分的转换失败。如果删除DISTINCT,则可以转换SQL。在您看到它的部分Status.Count()将其更改为Status.Distinct().Count(),您应该很好。