2014-12-04 82 views
1

我的LINQ查詢的LINQ to SQL,和與主連接表

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([T 0]。[數值] * [T 0]。[量])*

* T0.SUM([T 0]。[數值] * [T 0]。 [量])* - 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] 

回答

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