Linq To Sql,Sum和main以及连接表

时间:2014-12-04 22:21:10

标签: sql linq-to-sql

我的linq查询

from report in CustomerDayReports
join payments in CustomerPayments on new { report.CustomerId, report.CurrencyId } equals new {      payments.CustomerId, payments.CurrencyId } into j
from j2 in j.DefaultIfEmpty()
group report by new { report.CustomerId, report.CurrencyId } into g1
select new 
{ 
    Customer = g1.Key.CustomerId, 
    Currency = g1.Key.CurrencyId,
    Debt = g1.Sum(x => x.Value * x.Amount)
}

结果SQL

SELECT 
  SUM([t0].[Value] * [t0].[Amount]) AS [Debt],
  [t0].[CustomerId] AS [Customer], 
  [t0].[CurrencyId] AS [Currency]
FROM [CustomerDayReport] AS [t0]
LEFT OUTER JOIN [CustomerPayment] AS [t1] 
 ON ([t0].[CustomerId] = [t1].[CustomerId]) AND ([t0].   [CurrencyId] = [t1].[CurrencyId])
GROUP BY [t0].[CustomerId], [t0].[CurrencyId]

如何修改linq以获取下一个SQL?

* SUM([t0]。[Value] * [t0]。[Amount])*

* T0.SUM([t0]。[Value] * [t0]。[Amount])* - ISNULL(SUM([T1] .Amount)

SELECT 
  SUM([t0].[Value] * [t0].[Amount]) - ISNULL(SUM([t1].Amount), 0) AS [Debt],
  [t0].[CustomerId] AS [Customer], 
  [t0].[CurrencyId] AS [Currency]
FROM [CustomerDayReport] AS [t0]
LEFT OUTER JOIN [CustomerPayment] AS [t1] 
 ON ([t0].[CustomerId] = [t1].[CustomerId]) AND ([t0].   [CurrencyId] = [t1].[CurrencyId])
GROUP BY [t0].[CustomerId], [t0].[CurrencyId]

1 个答案:

答案 0 :(得分:0)

正确分组

group new {report, payments} by new { report.CustomerId, report.CurrencyId } into g

所有查询都是

 from report in CustomerDayReports
 join payments in CustomerPayments on new { report.CustomerId, report.CurrencyId } equals new {  payments.CustomerId, payments.CurrencyId } into j
 from payments in j.DefaultIfEmpty()
 group new {report, payments} by new { report.CustomerId, report.CurrencyId } into g
 select new 
 { 
     Customer = g.Key.CustomerId, 
     Currency = g.Key.CurrencyId,
     Debt = g.Sum(x => x.report.Value * x.report.Amount) - ((decimal?) g.Sum(x =>     x.payments.Amount) ?? (decimal?)0)
 }