数据是本地CSV文件,可通过OleDB加载到ado.net数据集中。该表有40多个由发票明细组成的列。每行是发票中的一个单独的行项目,可以包含1到n行。
该查询用于将发票明细分组到每张发票单行中,以合计发票金额和到期余额。
以下是我要尝试确定的方法:是否可以在单个查询中执行此操作?
//group the invoices by invoicenumber and sum the total
//Zoho has a separate record (row) for each item in the invoice
//first select the columns we need into an anon array
var invoiceSum =
DSZoho.Tables["Invoices"].AsEnumerable()
.Select (x =>
new {
InvNumber = x["invoice number"],
InvTotal = x["item price"],
Contact = x["customer name"],
InvDate = x["invoice date"],
DueDate = x["due date"],
Balance = x["balance"],
} );
//then group and sum
var invoiceTotals =
invoiceSum
.GroupBy (s => new {s.InvNumber, s.Contact, s.InvDate, s.DueDate} )
.Select (g =>
new {
InvNumber = g.Key.InvNumber,
InvDate = g.Key.InvDate,
DueDate = g.Key.DueDate,
Contact = g.Key.Contact,
InvTotal = g.Sum (x => Math.Round(Convert.ToDecimal(x.InvTotal), 2)),
Balance = g.Sum (x => Math.Round(Convert.ToDecimal(x.Balance), 2)),
} );
实际上,当您使用invoiceTotals的结果时,您只会执行一个查询。在显示的代码中,您甚至没有对数据库进行查询。
Google“ linq延迟执行”,很漂亮;-)
但是正如Uriil所说,您可以将语句合并为一个linq查询:
var invoiceSum =
DSZoho.Tables["Invoices"].AsEnumerable()
.Select (x =>
new {
InvNumber = x["invoice number"],
InvTotal = x["item price"],
Contact = x["customer name"],
InvDate = x["invoice date"],
DueDate = x["due date"],
Balance = x["balance"],
}
)
.GroupBy (s => new {s.InvNumber, s.Contact, s.InvDate, s.DueDate} )
.Select (g =>
new {
InvNumber = g.Key.InvNumber,
InvDate = g.Key.InvDate,
DueDate = g.Key.DueDate,
Contact = g.Key.Contact,
InvTotal = g.Sum (x => Math.Round(Convert.ToDecimal(x.InvTotal), 2)),
Balance = g.Sum (x => Math.Round(Convert.ToDecimal(x.Balance), 2)),
}
);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句