我如何使用linq对联接的查询进行分组

时间:2020-11-05 08:05:52

标签: c# sql linq

我正在尝试为图形生成一个数据集,该数据集将为我提供与以下SQL查询相同的结果:

select
    concat(year(InvoiceDate), '-', month(PaymentDate)) as Period,
    sum(InvoiceTable.InvoiceAmount) as BilledAmount,
    -sum(AccountTable.Payment) as IncomingPayments,
from InvoiceTable
left join AccountTable on InvoiceTable.InvoiceID = AccountTable.InvoiceID
where InvoiceTable.InvoiceDate >= cast('2019/01/01' as date) and InvoiceTable.InvoiceDate < cast('2020/01/01' as date)
group by concat(year(InvoiceDate), '-', month(PaymentDate))

但是,如果我尝试将其转换为linq查询,则无法获得相同的结果,或者无法访问联结的一侧或另一侧,或者每年获得的总数为另一边。

var data = from a in db.InvoiceTable
            where a.InvoiceDate >= FiscalYear.StartDate && a.InvoiceDate <= FiscalYear.EndDate
            join b in db.AccountTable on a.InvoiceID equals b.InvoiceID into ab
            from c in ab.DefaultIfEmpty()
            let period = string.Concat(a.InvoiceDate.Year, "-", a.InvoiceDate.Month)
            group a by period into g
            select new
            {
                Period = g.Key,
                Billed = g.Sum(o => o.InvoiceAmount),
                Collected = -b.Sum(o => (decimal?)o.Payment) ?? 0m //Can't access the right side anymore and if I group c I can't access the left side then
            };

我尝试在Collected列中嵌套另一个linq查询,但随后我将获得每个月的年度金额(g.Key)。

1 个答案:

答案 0 :(得分:1)

此查询应该有效。您必须将更多项目分组。另外,我还优化了您的查询按两个字段(而不是串联)进行分组。

var data = from a in db.InvoiceTable
        where a.InvoiceDate >= FiscalYear.StartDate && a.InvoiceDate <= FiscalYear.EndDate
        join b in db.AccountTable on a.InvoiceID equals b.InvoiceID into ab
        from b in ab.DefaultIfEmpty()
        group new { a, b } by new { a.InvoiceDate.Year, a.InvoiceDate.Month } into g
        select new
        {
            Period = g.Key.Year + "-" + g.Key.Month,
            Billed = g.Sum(o => o.a.InvoiceAmount),
            Collected = -b.Sum(o => (decimal?)o.b.Payment)
        };
相关问题