将求和与 Linq 结合使用 SQL

Using Having Sum with Linq to SQL

我有一个 SQL 命令,我正在尝试将其转换为 LINQ to SQL 命令,但遇到困难。

我的 SQL 命令如下:

SELECT purchs.iclientid, ifeatureid, AddnlOptionList FROM purchs
WHERE AddnlOptionList <> ''
GROUP BY purchs.iclientid, ifeatureid, AddnlOptionList
HAVING (SUM(noptions) > 0)

我已经成功地完成了以下示例:

var q =
   from purchs in db.Purchases
   group q by purchs.noptions into g
   where purchs.AddnlOptionList != ""
      && g.Sum(x => x.noptions) > 0
   select q;

但是,我似乎卡在了 q 组,出现了以下两个错误:

Cannot use local variable 'q' before it is declared

Cannot convert lambda expression to type 'System.Collections.Generic.IEqualityComparer<decimal?> because it is not a delegate type

来自 here 的一个例子说这应该有效,尽管它使用了连接,但我没有。任何帮助将不胜感激。

解决方案

我不得不稍微修改 Xiaoy312 的代码以获得我想要的,所以我想我会 post 在这里希望它可以帮助将来的人。感谢@Xiaoy312 的帮助

var updates = db.Purchases
   .Where(p => p.AddnlOptionList != "")
   .GroupBy(p => new { p.iclientid, p.ifeatureid, p.AddnlOptionList })
   .Where(g => g.Sum(p => p.noptions) > 0)
   .Select(g => g.Key);

您不能将 WHEREHAVING 子句都放在一个 where 中。我不太熟悉其他语法,所以这是方法语法之一:

var results = db.Purchases
    .Where(p => p.AddnlOptionList != "")
    .GroupBy(p => new { p.notions, p.iclientid, p.ifeatureid })
    .Where(g => g.Sum(p => p.notions) > 0)
    .SelectMany(g => g)

编辑:转换为 Linq 语法。

var results = from p in db.Purchases
              where p.AddnlOptionList != ""
              group p by new { p.notions, p.iclientid, p.ifeatureid } into g
              where g => g.Sum(p => p.notions) > 0
              from p in g
              select p;

编辑:我错过了 sql 命令。这意味着只拉组,而不是每个组中的每个项目。

// method syntax
db.Purchases
    .Where(p => p.AddnlOptionList != "")
    .GroupBy(p => new { p.notions, p.iclientid, p.ifeatureid })
    .Where(g => g.Sum(p => p.notions) > 0)
    .Select(g => g.Key)

// query syntax
    from p in db.Purchases
    where p.AddnlOptionList != ""
    group p by new { p.notions, p.iclientid, p.ifeatureid } into g
    where g.Sum(p => p.notions) > 0
    select new { g.Key.notions, g.Key.iclientid, g.Key.ifeatureid };