Reputation: 362
I am trying to convert an SQL query to LINQ where the query has 2 left joins and group by.
SELECT t1.Shop,t1.Stake, t2.Payout, t3.Anticipation FROM
(SELECT Shop, sum(Stake) AS 'Stake' FROM Bets GROUP BY Shop) t1
FULL OUTER join
(SELECT Shop, SUM(Amount) AS 'Payout' FROM Transactions where TransactionType = 1 GROUP BY Shop) t2 on t1.Shop = t2.Shop
FULL OUTER join
(SELECT Shop, sum(WinAmount) as 'Anticipation' from Bets where [Status] = 'W' group by Shop) t3 on t1.shop = t3.shop
This is the SQL query that works and below you can see the LINQ code that I have tried but it does not work
var obj = (from b in _context.Bets
group b by b.Shop into betsList
join t in _context.Transactions.Where(x = >x.TransactionType == TransactionType.Acceptance) on betsList.Key equals t.Shop
group t by t.Shop into transactionsList
from t in transactionsList.DefaultIfEmpty()
join ant in _context.Bets.Where(x = >x.Status == 'W') on b.Id equals ant.Id into anticipationList
from ant in anticipationList.DefaultIfEmpty()
select new {
Shop = betsList.Key,
Stake = betsList.Sum(k = >k.Stake),
Payout = transactionsList.Sum(x = >x.Amount),
Anticipation = anticipationList.Sum(x = >x.WinAmount)
}).ToList();
Sample output data from the SQL query is:
Upvotes: 0
Views: 147
Reputation: 27282
Better to divide query in small parts. This one should work, it is not FULL OUTER JOIN but, I think, with your data it may work:
var betsQuery =
from b in _context.Bets
group b by new { b.Shop } into g
select new
{
g.Key.Shop,
Stake = g.Sum(x => x.Stake)
};
var transactionQuery =
from t in _context.Transactions
where t.TransactionType == TransactionType.Acceptance
group t by new { t.Shop } into g
select new
{
g.Key.Shop,
Payout = g.Sum(x => x.Amount)
};
var antisipationQuery =
from b in _context.Bets
where b.Status == 'W'
group b by new { b.Shop } into g
select new
{
g.Key.Shop,
Anticipation = g.Sum(x => x.WinAmount)
};
var query =
from b in betsQuery
join t in transactionQuery on b.Shop equals t.Shop into tg
from t in tg.DefaultIfEmpty()
join a in antisipationQuery on b.Shop equals a.Shop into ag
from a in ag.DefaultIfEmpty()
select new
{
b.Shop,
b.Stake,
Payout = (double?)t.Payout,
Anticipation = (double?)a.Anticipation
};
var result = query.ToList();
Upvotes: 1