仅查询投票的最高价值

时间:2015-03-27 00:14:15

标签: c#

//query the list of winners of the said event
    public ActionResult List_of_Winners(int id=0) {
        var winners = (from cat in db.Events_Category_tbl
            join can in db.Candidates_Info_tbl on cat.events_category_id equals can.events_category_id
            where cat.events_info_id == id
            select new Candidates
            {
                events_category_name = cat.events_category_name,
                candidates_fullname = can.candidates_fullname,
                candidates_info_id = can.candidates_info_id,
                events_category_id = cat.events_category_id,
                no_of_votes = can.no_of_votes.Value
            }).Take(1).OrderBy(x=>can.no_of_votes);

        return PartialView(winners);
    }

在此代码中,Iam计划在每个类别中获得最高的no_of_votes。但是,我收到了这个错误。我如何查询数据库以获取我想要的数据?

这是显示的错误:"名称'可以'在当前上下文中不存在"

1 个答案:

答案 0 :(得分:1)

你需要移动你拥有orderby / take的地方,我相信这样的事情应该有效:

var winners = from cat in db.Events_Category_tbl
              from can in
                  (from c in db.Candidates_Info_tbl
                   where c.events_category_id == cat.events_category_id
                   select c).OrderByDescending(c => c.no_of_votes).Take(1)
              where cat.events_info_id == id
              select new Candidates
              {
                  events_category_name = cat.events_category_name,
                  candidates_fullname = can.candidates_fullname,
                  candidates_info_id = can.candidates_info_id,
                  events_category_id = cat.events_category_id,
                  no_of_votes = can.no_of_votes.Value
              };

对于这样的关系,这样的事情可能有用(应该归功于每个类别得分最高的所有人):

var winners = from cat in db.Events_Category_tbl
              from max_votes in
                  (from c in db.Candidates_Info_tbl
                   where c.events_category_id == cat.events_category_id
                   select c.no_of_votes).OrderByDescending(c => c).Take(1)
              join can in db.Candidates_Info_tbl on cat.events_category_id equals can.events_category_id
              where cat.events_info_id == id && can.no_of_votes == max_votes
              select new Candidates
              {
                  events_category_name = cat.events_category_name,
                  candidates_fullname = can.candidates_fullname,
                  candidates_info_id = can.candidates_info_id,
                  events_category_id = cat.events_category_id,
                  no_of_votes = can.no_of_votes.Value
              };

我也可以用GroupBy或不同的样式内部查询来完成,但是那个'来自x in(来自y中的y,其中y.something = x.something选择了一些东西).Take(n)'模式结果SQL服务器中的cross/outer apply在我见过的大多数情况下表现都很好。