2

これがSQLクエリです

Select sum(f.Acres*m.credit1), sum(f.Acres*m.credit2), sum(f.Acres*m.credit3)
from first f join model m on f.Id = m.fID
where m.year == 2012

LINQでSQLの上にこれを書く方法は?

ありがとう!

4

1 に答える 1

2

集計を行うにはグループが必要なため、これを Linq で行うのは少しトリッキーです。以下のようなダミー値でグループ化すると、機能します。

var q = from f in first
        join m in model on f.Id equals m.fID
        where m.year == 2012
        group new { f, m } by 1 into g
        select new 
        { 
           credit1 = g.Sum(x => x.f.Acres * x.m.credit1),
           credit2 = g.Sum(x => x.f.Acres * x.m.credit2),
           credit3 = g.Sum(x => x.f.Acres * x.m.credit3)
        };

編集
コメントを読んでから。年ごとにグループ化したい場合は、次のようにします。

var q = from f in first
        join m in model on f.Id equals m.fID
        where m.year >= 2014 && m.year <= 2020
        group new { f, m } by m.year into g
        select new 
        { 
           year    = g.Key,
           credit1 = g.Sum(x => x.f.Acres * x.m.credit1),
           credit2 = g.Sum(x => x.f.Acres * x.m.credit2),
           credit3 = g.Sum(x => x.f.Acres * x.m.credit3)
        };
于 2012-10-29T22:52:24.443 に答える