我在TSQL中有一个查询,我试图将其转换为LINQ以便在我们的Web应用程序中使用,但我真的在努力解决这个问题。它是带有EF6的MVC5,数据库是SQL Server 2008 R2。任何帮助表示赞赏!
SQL查询
select MAX(ShipFromCompanyName) as Supplier, COUNT(*) as AllSupplierCount,
SUM(isnull(cast(TransportationCharges as decimal(18,2)),0)) as AllFreightCharges,
SUM(isnull(cast(TransportationCharges as decimal(18,2)),0)) * .45 as FreightSavings
from table
group by ShipFromCompanyName
order by ShipFromCompanyName
ShipFromCompanyName
和TransportationCharges
都作为varchar存储在数据库中,遗憾的是我无法将TransportationCharge
的数据类型更改为小数
LINQ
var Scorecard = (from upsid in _db.table select upsid).GroupBy(x => new { x.ShipFromCompanyName, x.TransportationCharges })
.Select(x => new
{
x.Key.ShipFromCompanyName,
SupplierCount = x.Count(),
FreightCharges = x.Key.TransportationCharges.Cast<decimal>().Sum(),
}).ToList();
答案 0 :(得分:0)
我认为您需要在处理后进行操作,而不是让SQL执行此操作。让SQL做尽可能多的事情然后在内存中做其余的事情
var Scorecard = (from upsid in _db.table select upsid).GroupBy(x => new { x.ShipFromCompanyName, x.TransportationCharges })
.Select(x => new
{
x.Key.ShipFromCompanyName,
SupplierCount = x.Count(),
FreightCharges = x.Key.TransportationCharges,
}).AsEnumerable()
.Select (x => new
{
ShipFromCompanyName = ShipFromCompanyName ,
SupplierCount = SupplierCount ,
FreightCharges = FreightCharges.Cast<decimal>.Sum() ,
}
没有测试过这段代码,但它应该会给你一个想法。
答案 1 :(得分:0)
var Scorecard = (from upsid in _db.table select upsid)
.GroupBy(x => new { x.ShipFromCompanyName, x.TransportationCharges })
.Select(x => new
{
x.Key.ShipFromCompanyName,
SupplierCount = x.Count(),
FreightCharges = x.Key.TransportationCharges.Select(tc=>decimal.Parse(tc)).Sum()*0.45,
}).ToList();
由于我不明白你的查询我不确定,但这可能有用。