如何在LINQ中编写SQL查询?

时间:2009-03-20 04:18:34

标签: sql linq

我有一张看起来像这样的桌子。查询需要返回每个位置的最后日期条目。我将如何在SQL和LINQ中编写它?

Id  Location        Salary  Date
1   Los Angeles     $1500   Jan-05-1999 
2   San Diego       $250    Jan-07-1999 
3   Los Angeles     $300    Jan-08-1999
4   Boston          $700    Jan-08-1999
5   Los Angeles     $300    Jan-08-1999

结果将是:

2   San Diego       $250    Jan-07-1999
4   Boston          $700    Jan-08-1999
5   Los Angeles     $300    Jan-08-1999

6 个答案:

答案 0 :(得分:1)

请记住,我很新的链接,我不认为这是最好的方式:

var collection = from d in <TABLE> select d;
collection = collection.GroupBy(x => x.Date).Select(x => x.Last());

基本上只是在日期组,并采取最后一个。我想不出在LINQ命令中执行此操作的好方法,所以我只选择了所有行 - 任何人都知道将这些行组合起来?

答案 1 :(得分:1)

如果您的日期包含时间,那么您可以:

var locations = 
   from l in mycontext.Locations
   where l.Date = mycontext.Locations
         .Where(l2=>l.Location == l2.Location)
         .Max(l2.Date)
   select l;

或者,假设ID是一个标识,并且记录在它们出现时插入到表中(您的示例似乎提示如此),您可以这样做:

var locations = 
   from l in mycontext.Locations
   where l.ID = mycontext.Locations
         .Where(l2=>l.Location == l2.Location)
         .Max(l2.ID)
   select l;

答案 2 :(得分:0)

SELECT location, max(date)

FROM yourtable

GROUP BY location

编辑:我没有看到结果被要求或不确定它是否最初存在:

SELECT yourtable.id, yourtable.location, yourtable.salary, yourtable.date
FROM yourtable INNER JOIN
  (SELECT yourtable.location, MAX(yourtable.date) as thedate
   FROM yourtable
   GROUP BY yourtable.location) AS MYRESULT 
   on MYRESULT.thedate = yourtable.date  
      AND MYRESULT.location = yourtable.location

虽然没有测试过。

答案 3 :(得分:0)

@Bobby Shaftoe

我相信他正在寻找最新的条目,而不是每个地点的最新日期。如果我的假设是正确的,那就更像是

SELECT max(ID),location,date
FROM tablename
GROUP BY location

答案 4 :(得分:0)

要获得每个位置的最大日期的整行,我认为SQL是:

SELECT t1.Id, t1.Location, t1.Salary, t1.Date
FROM YourTable t1, 
    (SELECT Location, MAX(Date) AS MaxDate
    FROM YourTable
    GROUP BY Location) t2
WHERE t1.Location = t2.Location
AND t1.Date = t2.MaxDate

如果我错了,请纠正我!

答案 5 :(得分:0)

实际上,如果我正确地阅读这个问题,这不是那么直截了当。由于洛杉矶在最大日期有2个条目,因此似乎还有一个规则,即在这种情况下应选择最大ID。

在这种情况下,SQL变得有点复杂,需要2个分组....

select id, location, salary, date from 
locations where id in
(select  max(id) as MaxID
from locations where date in (
Select Max(Date) as MaxDate from Locations group by Location)
Group by location)

相应的Linq查询,还需要2个分组...

  var qry = from a in locations
            group a by a.Location into grp
            from b in grp
            where b.Date == grp.Max(o => o.Date)
            group b by b.Location into grp2
            from c in grp2
            where c.ID == grp2.Max(obj => obj.ID)
            orderby c.ID
            select c;