简体   繁体   English

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

[英]How can I group a joined query with linq

I'm trying to produce a data set for a graph that would get me the same result as the following SQL query:我正在尝试为图表生成一个数据集,该数据集将得到与以下 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))

But if I try to translate it into a linq query, I can't get the same result, I either don't have access to one or the other side of the junction, or I get a yearly total of one or the other side.但是,如果我尝试将其转换为 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
            };

I tried to nest another linq query in the Collected column but then I would get the yearly amount on each month ( g.Key ).我试图在Collected列中嵌套另一个 linq 查询,但随后我会得到每个月的年度金额 ( g.Key )。

This query should work.这个查询应该可以工作。 You have to include into grouping more items.您必须将更多项目包含到分组中。 Also I have optimized your query do group by two fields, not a concatenation.我还优化了您的查询 do group by 两个字段,而不是串联。

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)
        };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM