How do I convert the following query into a Linq expression?
SELECT p.playerid,
(SELECT SUM(d.runs)
FROM deliveries d
INNER JOIN overs o ON d.overid = o.overid
WHERE o.isbatting = 1
AND o.gameid = 5
AND d.player_playerid = playerid) AS runsfor,
(SELECT SUM(d.runs)
FROM deliveries d
INNER JOIN overs o
ON d.overid = o.overid
WHERE o.isbatting = 0
AND o.gameid = 5
AND d.player_playerid = playerid) AS runsagainst,
( (SELECT SUM(d.runs)
FROM deliveries d
INNER JOIN overs o ON d.overid = o.overid
WHERE o.isbatting = 1
AND o.gameid = 5
AND d.player_playerid = playerid) -
(SELECT SUM(d.runs)
FROM deliveries d
INNER JOIN overs o ON d.overid = o.overid
WHERE o.isbatting = 0
AND o.gameid = 5
AND d.player_playerid =
playerid) ) AS runscontributed
FROM deliveries d
INNER JOIN players p ON d.player_playerid = p.playerid
INNER JOIN overs o ON d.overid = o.overid
WHERE o.gameid = 1
GROUP BY p.playerid
The results generated look like:
2 13 16 -3
4 -5 18 -23
5 -6 11 -17
7 4 1 3
8 5 7 -2
9 12 17 -5
10 -4 24 -28
12 19 1 18
Start out by simplifying.
Then simplify some more…
Lather, rinse, repeat:
I’m not certain this will do what you want, but it should give you a jumping off point.
Don’t use this code directly; I wrote it freehand, and I’m not sure it will work the first time without some tweaking. The real point here is to simplify. Break your SQL query into smaller groups and write the LINQ for those. Then write some more LINQ to tie it all together. The ability to do that is one of the best things about LINQ.