代码之家  ›  专栏  ›  技术社区  ›  Dean

在C中将SQL查询(带相关子查询)转换为LINQ#

  •  6
  • Dean  · 技术社区  · 16 年前

    我正在寻找一些帮助,将下面的sql查询转换为LINQ,并将其转换为C#中的实体。

    SELECT f.FundId, u.UnitValue
    FROM Fund f
    INNER JOIN FundUnit u ON f.FundId= u.FundId
    WHERE u.EffectiveDate = (SELECT MAX(effectivedate) 
                             FROM FundUnit k 
                             WHERE u.FundId = k.FundId)
    AND f.Active = 1
    ORDER BY f.FundId
    

    查询将读取数据库中的所有活动资金及其最新单位值。包含每个基金记录的基金表。fund unit表包含每个基金在每个日期的单位值记录。以前日期的单位值也保留在表中以保持历史记录。

    并非所有基金每天都收到新的单位价值,因此所有基金的最新生效日期不一定相同。因此,需要将max(effectivedate)函数应用于units表,需要将其应用于每个基金,因此需要应用相关的子查询。

    谢谢

    2 回复  |  直到 16 年前
        1
  •  6
  •   Bruno Brant    16 年前

    为了回答这个问题,我必须假设你的实体的名字。

    从Fund中选择f.FundId,u.UnitValue f内部连接FundUnit u ON f.FundId= u.FundId,其中u.EffectiveDate= (选择最大值(生效日期) 来自FundUnit k 其中u.FundId=k.FundId)和f.Active=1 按f.FundId订购

    我将假设一个基金实体和一个基金单位实体,就像这个例子一样。

    var query = from f in Fund 
                from u in FundUnit
                where f.FundId == u.FundId
                && u.EffectiveDate == (from k in FundUnit
                                       where u.FundId = k.FundId
                                       select EffectiveDate).Max()
                && f.Active == 1
                select new { Id = f.FundId, EffectiveDate = u.EffectiveDate } // Add any fields you need
                order by f.FundId
    

    我是凭记忆做的,没有测试,可能有一些小问题。如果我有时间,我会测试的。

        2
  •  0
  •   Kell    16 年前

    我认为这应该有帮助: directly execute sql strings