2013-01-12 60 views
0

我怎麼能複製在LINQ的GroupBy +案例當總和(X)> 0,則總和(x)的其他0

SELECT KEY_COLUMN, 
     CASE WHEN SUM(COLUMN2) < 0 THEN SUM(COLUMN2) ELSE 0 END AS NewColumn 
FROM TABLE 
GROUP BY KEY_COLUMN 

下到現在我能想出以下

var result = from a in source 
       group a by a.Key_Column 
        into g 
        select new 
        { 
         Key_Column = g.Key, 
         NewColumn = g.Where(item => item.Column2 < 0) 
            .Sum(item => item.Column2) 
}; 
以上

在決定它是否爲負數之前,代碼並沒有真正總結Column2。

回答

2
var query = from a in db.Table 
      group a by a.Key_Column into g 
      let sum = g.Sum(item => item.Column2) 
      select new { 
       Key_Column = g.Key, 
       NewColumn = sum < 0 ? sum : 0 
      }; 
+1

不錯,感謝lazyberezovsky – Pak

+0

我相信你的版本是更有效的,但是當我有太多的列來做到這一點各類有條件的東西拿出一個值,你推薦使用我做的方式在我的回覆下面? (對不起,無法在此評論中對其進行格式化,因此我將其發佈爲答案) – Pak

0

是不是這樣?

var query = from r in db.Table 
    group r by r.KEY_COLUMN into g 
    select new { 
    KEY_COLUMN = g.Key, 
    NewColumn = g.Sum(x => x.COLUMN2) < 0 ? g.Sum(x => x.COLUMN2) : 0 
}; 
+0

幾乎在這種情況下,總和將被計算兩次 –