2013-02-25 187 views
0

我有一個SQL查詢:LINQ查詢與子where子句

SELECT [Paypoint] 
     ,[Department] 
     ,[EmployeeCode] 
     ,[Gender] 
     ,[EmployeeTitle] 
     ,[Initials] 
     ,[Surname] 
     ,[ItemsIssuedDate] 
     ,[ItemsIssuedStockNumber] 
    FROM [MyTable] AS a 
    WHERE 
(
     [ItemsIssuedDate] = ( SELECT  max([ItemsIssuedDate]) 
           FROM  [MyTable] AS b 
           WHERE  a.[Paypoint] = b.[Paypoint] 
              AND a.[Department] = b.[Department] 
              AND a.[EmployeeCode] = b.[EmployeeCode] 
              AND a.[Gender] = b.[Gender] 
              AND a.[Surname] = b.[Surname] 
          ) 

一個人怎麼會得到比較性LINQ查詢?我不能使用SQL查詢的數據已經是一個DataSet,現在需要進一步修改...

我已經嘗試,但是這並不工作:

 var query = from a in excelTable 
        where 
        (
         from c in excelTable 
         group c by new 
         { 
          c.Paypoint, 
          c.EmployeeCode 
         } into g 
         where string.Compare(a.Paypoint, g.Key.Paypoint) == 0 && string.Compare(a.EmployeeCode, g.Key.Paypoint) == 0 
         select g.Key.Paypoint 
        ) 
        select a; 

回答

0

你最直接用SQL查詢將是:

var query = 
    from a in excelTable 
    let maxIssueDate = 
     (from b in excelTable 
     where a.Paypoint == b.Paypoint && 
      a.Department == b.Department && 
      a.EmployeeCode == b.EmployeeCode && 
      a.Gender == b.Gender && 
      a.Surname == b.Surname 
     select b.ItemsIssueDate).Max() 
    where a.ItemsIssueDate == maxIssueDate 
    select a; 
+0

謝謝,這個作品 - 使其更快的任何方式....查詢在後臺工作中運行約需6分鐘... – JayT 2013-02-25 18:35:17

2
var query = from a in MyTable 
      group a by new { 
       a.Paypoint, 
       a.Department, 
       a.EmployeeCode, 
       a.Gender, 
       a.Surname 
      } into g 
      select g.OrderByDescending(x => x.ItemsIssuedDate) 
        //.Select(x => new { required properties }) 
        .First();  

你也可以選擇僅包含必填字段的匿名對象。由你決定。

+0

不幸的是,這只是每個日期返回一個項目,如果有很多項目有相同的日期,它不工作... – JayT 2013-02-25 18:31:54