linq-to-sql:SELECT部分​​中的GROUP BY和MIN()

时间:2013-09-22 03:56:49

标签: c# mysql linq linq-to-sql

在MySql中,我有以下(简化)查询:

SELECT 
  ct.ColumnA, 
  MIN(IF(Constant + mt.ColA >= mt.ColB, Constant + mt.ColA, mt.ColB)) AS ResultCol
FROM 
  master_table mt
    INNER JOIN child_table ct ON (ct.MasterID = mt.ID)
WHERE
  ct.ColumnB = 1
  ...
GROUP BY
  ct.ColumnA;

此查询在MySql中完美运行,但我无法将其转换为Linq2sql。

1 个答案:

答案 0 :(得分:0)

好的,这就是我完成的方法(没有使用linq2sql测试它,我使用linq2db项目):

var q = 
  from mt in db.MasterTable
  join ct in db.ChildTable on mt.ID equals ct.MasterID
  where
    ct.ColumnB = 1 &&
    ...
  group new { ct, mt } by new { ct.ColumnA } into g
  select
    new
    {
      g.Key.ColumnA,
      ResultCol = g.Min(x => myConstant + x.mt.ColA > x.mt.ColB
                                ? myConstant + x.mt.ColA
                                : x.mt.ColB)
    };