0

我需要在常规 sql 查询命令中构造一个这样的 linq:

select t1.vendorcode, t1.location, sum(t1.sales)
from table1 t1
where t1(vendorCode, location) in
      (select t2.vendorCode, t2.location from table2 t2) 
groupby t1.vendorCode, t1.location

我构造linq如下:

query = from t1 in table1
where ...
join t2 in table2 on new
{
  t2.vendorcode, t2.location
} equals new
{ 
  t1.vendorcode, t1.location 
}

我的问题是:我应该如何构建这个 linq?我需要另一个子查询还是可以添加更多group by并选择语句来完成这个 linq?

4

2 回答 2

1

您不需要添加另一个group by子句 - 您只需要选择总和:

var query = from t1 in table1
            join t2 in table2 
              on new { t1.vendorcode, t1.location } equals
                 new { t2.vendorcode, t2.location }
            group t1 by new { t1.vendorcode, t1.location } into g
            select new { 
                g.Key.vendorcode,
                g.Key.location, 
                g.Sum(t1 => t1.sale)
            };

如果table2任何特定的供应商代码/位置对中只有一条记录,这将起作用。但是,如果可以有多个这样的记录,那么它就不起作用 - 你可能想要更多类似的东西:

var query = from t1 in table1
            where table2.Select(t2 => new { t2.vendorcode, t2.location })
                        .Contains(new { t1.vendorcode, t1.location })
            group t1 by new { t1.vendorcode, t1.location } into g
            select new { 
                g.Key.vendorcode,
                g.Key.location, 
                g.Sum(t1 => t1.sale)
            };

从逻辑上讲,这就是您的“存在”版本。

于 2013-01-29T06:48:50.847 回答
0

这应该这样做

var query =
    from t1 in table1

    join t2 in table2
    on new { vc = t1.vendorcode, lc = t1.location }
    equals new { vc = t2.vendorcode, lc = t2.location }

    group t1 by new { vc = t1.vendorcode, lc = t1.location };
于 2013-01-29T06:38:58.123 回答