2016-05-24 113 views
0

你好,我有sql查詢組通過查詢有沒有在子查詢LINQ

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; 

你能請在我的代碼中提及錯誤。

回答

0

您的SQL查詢是錯誤的,當你GROUPBYcolumn1,你只能選擇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已經返回每組只有1行