难以在LINQ中写这个

时间:2012-09-21 08:07:58

标签: linq

该应用程序是一个基本的股票分析应用程序。

数据集如下所示:

`ABC,True,21/09 / 2012,101.34

ABC,False,21/09 / 2012,202.45

CDE,True,21/09 / 2012,345.67

ABC,True,22/09/2012。 456.78

` SQL在这里:

SELECT TickerCode, Australian from Stk_ClosingPrices group by TickerCode,
 Australian having count(*) >= @daysToAverageOver order by TickerCode 

我想要的结果是前两个字段的分组,以及每个组中的数量。对于上述情况,将是:

ABC,是的,2 ABC,False,1 CDE,True,1

然后我想只返回那些有Count>参数传入。

该算法将计算一个20天的移动平均线,因此在英文中查询是“给我20个以上数据记录的股票的钥匙”

这是我已经走了多远,但是我无法得到正确的计数,对于每一组来说都是一样的。

  var query = (from cp in this.ObjectContext.stk_ClosingPrices group cp by new {
       cp.TickerCode, cp.Australian
   }
   into grp
    select new {
       grp.Key.TickerCode, grp.Key.Australian,
       Count = grp.Distinct()
   }).ToList();

我见过类似 grp.Sum(Quantity)的示例,但似乎无法将其重新强制转换为.Count()谓词。

非常感谢,

1 个答案:

答案 0 :(得分:0)

尝试

var query1 = (from cp in this.ObjectContext.stk_ClosingPrices group cp by new {
   cp.TickerCode, cp.Australian
}
into grp
select new {
   grp.Key.TickerCode, grp.Key.Australian,
   Count = grp.Count()
});

var results = (from r in query where r.Count > 20 orderby r.TickerCode select r).ToList();

实际上会产生类似

的SQL
SELECT TickerCode, Australian, Count
FROM (
    SELECT COUNT(*) AS Count, TickerCode, Australian
    FROM  Stk_ClosingPrices
    GROUP BY TickerCode, Australian
    ) AS t1
WHERE t1.Count > 20
Order By t1.TickerCode