tags:

views:

39

answers:

2

So I am trying to write something like this:

SELECT  s.CompanyID, 
        s.ShareDate, 
        s.OutstandingShares, 
        s.ControlBlock 
FROM (
    SELECT MAX(ShareDate) AS Sharedate, 
           CompanyID
    FROM ShareInfo
    WHERE (ShareDate <= @filter_date)
    GROUP BY CompanyID
 ) AS si 
 INNER JOIN
 tblShareInfo AS s ON s.ShareDate = si.Sharedate AND s.CompanyID = si.CompanyID

Essentially this is trying to return the most recent Share Information, we keep a running history. Now I am trying to write something similar to this in LINQ.

Here was my closest attempt:

From a _
In db_context.ShareInfos _
Where a.ShareDate <= filter_date _
Group a By a.CompanyID Into Group _
Select CompanyID, MostRecentShareDate = Group.Max(Function(a) a.ShareDate) _
Join b In db_context.ShareInfos On b.CompanyID Equals a.CompanyID _
Select b.CompanyID, b.ShareDate, b.OS, b.CB()

Unfortunately this does not compile. Obviously I'm not understanding the LINQ syntax somehow. Can anyone steer me in the right direction?

Thanks.

A: 

with your last select statement you should use

select new {

CompanyID = b.CompanyID,
ShareDate = b.ShareDate,
OS = b.OS,
CB = b.CB
};

that's a start...

Tony
This is C# syntax, btw...
Tony
I guess I should mention that the part that does not compile is the line with the Join on it. The 'a.CompanyID' at the very end of the line gives the error "Name 'a' is not declared or not in current scope"
BitFiddler
A: 

Okay so looks like this needs to be done using two statements:

Dim MostRecentShareDates = _ 
From s2 In query_collection.DBContext.ShareInfos _
Where s2.ShareDate <= filter_date _
Group s2 By s2.CompanyID Into Group _
Select New With { _
                    .CompanyID = CompanyID, _
                    .MostRecentShareDate = Group.Max(Function(s3) s3.ShareDate) _
                }

Return From s In query_collection.DBContext.ShareInfos _
       Join s1 In MostRecentShareDates On s.CompanyID Equals s1.CompanyID And s.ShareDate Equals s1.MostRecentShareDate _
       Select New With { _
                        .CompanyID = s.CompanyID, _
                        .ShareDate = s.ShareDate, _
                        .OS = s.OS, _
                        .CB = s.CB _
                       }

I tried using the 'Let' keyword to embed the first statement into the second, but that would not compile either. Now the nice thing about this is the Linq has delayed execution, so until you traverse the collection returned by the second statement, no SQL gets generated. Linq is then smart enough to combine the two code fragments into one SQL statement, essentially exactly the same statement as I wrote in my original SQL above.

BitFiddler