2015-08-14 45 views
0

我有一個SQL命令,我試圖轉換爲LINQ to SQL命令,但有困難。使用總結與Linq到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; 

但是,我似乎被困在以下兩個錯誤組問:

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的例子說,這應該工作,雖然它使用加入,而我不是。任何幫助,將不勝感激。

SOLUTION

我不得不修改Xiaoy312的代碼一點點地得到我想要的東西,所以我想我會在這裏發佈,希望它可以幫助別人的未來。謝謝@ 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); 
+0

爲什麼在查詢中使用'q'?你不應該'......用......組合'嗎? – juharr

+0

@juharr - 這就是我從我跟蹤的樣本中得到的。當我將其更改爲「group purchs by」時,我的where子句停止工作 - 不包含定義... – Tim

+1

該示例具有'group c by ...',它以'from db.City'中的c開頭。基本上你必須將你從源頭拉出來的東西組合在一起。現在,您正在嘗試將想要分配結果的本地變量進行分組。 – juharr

回答

4

你不能把兩者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 }; 
+0

爲您進行了轉換;) – Aron

+0

@Aron您確定要執行「SelectMany」嗎? – juharr

+0

@juharr我的壞:P – Aron