如果不存在,则选择一些数据

时间:2017-06-05 13:28:54

标签: sql sql-server linq sql-server-2008 linq-to-sql

我写了一个从tbl中选择最高记录的查询。我想检查tbl中是否有记录我的查询返回假数据(StudentId = 1,HighScore = 0)

var queryWin = (from T in ((from tbl_ActPoints in dc.tbl_ActPoints
                select new
                {
                    tbl_ActPoints.StudentId,
                    tbl_ActPoints.Score
                }))
    group T by new
    {
        T.StudentId
    } into g
    orderby
      ((System.Int32?)g.Sum(p => p.Score) ?? (System.Int32?)0) descending
    select new
    {
        g.Key.StudentId,
        HighScore = ((System.Int32?)g.Sum(p => p.Score) ?? (System.Int32?)0)
    }).Take(1);

2 个答案:

答案 0 :(得分:0)

试试这个:

${__StringFromFile(/path/to/your/file.csv,,,)}

答案 1 :(得分:0)

稍微清理你的代码:

var queryWin = (from tbl_ActPoints in dc.tbl_ActPoints
                group new
                {
                    tbl_ActPoints.StudentId,
                    tbl_ActPoints.Score
                } by tbl_ActPoints.StudentId into g
                orderby
                  (g.Sum(p => p.Score) ?? 0) descending
                select new StudentHighScore
                {
                    g.Key.StudentId,
                    HighScore = (g.Sum(p => p.Score) ?? 0)
                }).FirstOrDefault() 
                     ?? new StudentHighScore { StudentID = 1, HighScore = 0};

诀窍和coolswastik的代码不起作用的原因,因为即使具有相同的属性,两个匿名对象总是不同的,所以你需要一个命名类:

class StudentHighScore
{
    public int StudentId { get; set; }
    public int HighScore { get; set; }
}