按查询分组,不在子查询linq中

时间:2016-05-24 11:06:12

标签: c# sql asp.net linq

您好sql查询

SELECT DISTINCT column1 ,column2 ,column3 FROM tableA
WHERE column1 NOT IN (SELECT column1 FROM tableA WHERE DATE(column2) <= '2016-05-01') AND column4 != 'Bonus'GROUP BY column1 

我尝试将其转换为linq查询,以下是我尝试过的示例代码

 var value = from name in DB.tableA
 where name .column4 != "Bonus" && !(from name2 in DB.tableA
 where name2.column2.Day >= 1 && name2.column2.Month == today.Month && name2.column2.Year == today.Year
select new { name2.column1, name2.column2, name2.column3 })
group customer by name.column1 into Agroup
select Agroup;

请您在我的代码中提及错误。

1 个答案:

答案 0 :(得分:0)

您的SQL查询错误,当您GROUPBY column1时,您只能在其他列上选择column1或使用Aggregate函数(SUM,AVG ,MAX ......)

你可以这样做:

DateTime queryDate = new DateTime(2016, 05, 01);

var value = from name in DB.tableA
            where name.column4 != "Bonus" &&
            DB.tableA.Any(x=> x.column2.Date <= queryDate && x.column1 == name.column1)
            group name by name.column1 into grp
            select new
            {
                Column1 = grp.Key,
                // you can use grp.key, grp.SUM(), grp.MAX(), grp.MIN(), grp.Count() ...
                // to execute aggregate over each group

            };

此外,将DistinctGroupBy一起使用毫无意义。 GroupBy已为每个组返回仅一行。