Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 如果不存在,请选择一些数据_Sql_Sql Server_Linq_Sql Server 2008_Linq To Sql - Fatal编程技术网

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

Sql 如果不存在,请选择一些数据,sql,sql-server,linq,sql-server-2008,linq-to-sql,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中选择最高记录的查询。我想检查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);

var result = queryWin.FirstOrDefault();

if (result == null)
  result = new { StudentId = 1, HighScore=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; }
}

编辑了答案
class StudentHighScore
{
    public int StudentId { get; set; }
    public int HighScore { get; set; }
}