LINQ to Sql组并在子查询中求和但占空​​值

时间:2013-11-18 19:22:44

标签: linq linq-to-sql

我有以下查询按预期工作,直到它从数据库中达到null值。

var accounts = from p in db.PSR_FINAL_DATAs
            join c in db.PROJ_CUSTOMs on p.PROJ_ID equals c.PROJ_ID
            where !SqlMethods.Like(p.ACCT_ID, "%704-10-12%") &&
                    !SqlMethods.Like(p.ACCT_ID, "%-01%") &&
                    !SqlMethods.Like(p.ACCT_ID, "%706-10-12%") &&
                    SqlMethods.Like(p.PROJ_ID, "70000.%") &&
                    p.FY_CD == "2014"
            group p by new
            {
                p.ACCT_ID,
                p.PROJ_ID,
                c.PROJ_NAME
            }
                into s
                select new
                {
                    Project = s.Key.PROJ_ID,
                    Account = s.Key.ACCT_ID,
                    ProjectNumber = s.Key.PROJ_NAME,
                    July = s.Where(a => a.PD_NO == 1).Sum(b=> b.PTD_INCUR_AMT),
                    Aug = s.Where(a => a.PD_NO == 2).Sum(b => b.PTD_INCUR_AMT),
                    Sep = s.Where(a => a.PD_NO == 3).Sum(b => b.PTD_INCUR_AMT),
                    Oct = s.Where(a => a.PD_NO == 4).Sum(b => b.PTD_INCUR_AMT),
                    Nov = s.Where(a => a.PD_NO == 5).Sum(b => b.PTD_INCUR_AMT),
                    Dec = s.Where(a => a.PD_NO == 6).Sum(b => b.PTD_INCUR_AMT),
                    Jan = s.Where(a => a.PD_NO == 7).Sum(b => b.PTD_INCUR_AMT),
                    Feb = s.Where(a => a.PD_NO == 8).Sum(b => b.PTD_INCUR_AMT),
                    Mar = s.Where(a => a.PD_NO == 9).Sum(b => b.PTD_INCUR_AMT),
                    Apr = s.Where(a => a.PD_NO == 10).Sum(b => b.PTD_INCUR_AMT),
                    May = s.Where(a => a.PD_NO == 11).Sum(b => b.PTD_INCUR_AMT),
                    June = s.Where(a => a.PD_NO == 12).Sum(b => b.PTD_INCUR_AMT),
                    Total = string.Format("{0:C}", s.Sum(y => y.PTD_INCUR_AMT))
                };

如何修改查询s.Where(a => a.PD_NO == 1).Sum(b=> b.PTD_INCUR_AMT)以考虑空值?

编辑:

我尝试了以下s == null ? 0 : s.Where(a => a.PD_NO == 5).Sum(b => b.PTD_INCUR_AMT),但这是我收到的错误消息:

The null value cannot be assigned to a member with type System.Decimal which is a non-   nullable value type.

1 个答案:

答案 0 :(得分:1)

好的,只是想通了......这是解决方案:

s.Where(a => a.PD_NO == 'whatever').Sum(b => (decimal?)b.PTD_INCUR_AMT)