I would like to query a table (Accounts) and also as part of the query get totals (Total) from another table (AccountPositions). How can I rewrite this sql query as a linq query? Is it as easy as adding a group by statement... but the group by usage is confusing me.
select
(select sum(ap.Quantity * ap.LastPrice) from AccountPositions ap
where ap.AccountId = a.Accountid and ap.IsOpen = 0) as Total,
a.AccountId, a.Username, a.FirstName, a.LastName, a.AccountNumber
from Accounts a
where a.IsTrading = 1
Something like???
var query = (from a in _context.Accounts
join ap in _context.AccountPositions on ap.AccountId = a.AccountId
where a.IsTrading == true && and ap.IsOpen == true
select new {
Total = ap.Sum(r => r.Quantity * r.LastPrice),
AccountId = a.AccountId,
Username = a.Username,
FirstName = a.FirstName,
LastName = a.LastName,
AccountNumber = a.AccountNumber
});
Desired Result:
Total AccountId Username FirstName LastName AccountNumber
2500 496 brice Brian Rice U399445
160 508 jdoe John Doe U555322
Tables:
Accounts
AccountId Username FirstName LastName AccountNumber IsTrading
496 brice Brian Rice U399445 1
498 bmarley Bob Marley U443992 0
508 jdoe John Doe U555332 1
AccountPositions
AccountPositionId AccountId Quantity LastPrice IsOpen
23 496 10 200 1
24 496 15 48 0
25 508 8 20 1
26 498 18 35 1
27 496 5 100 1