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.g开发者_JAVA百科ameid = 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.
SELECT d.*, o.*
FROM deliveries d
INNER JOIN overs o ON d.overid = o.overid
var joined = from d in deliveries
join o in overs on d.overid equals o.overid
select new { d, o };
Then simplify some more...
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
(from j in joined
where j.o.isBatting
&& j.o.gameId == 5
&& j.d.player.playerId == playerId
select j.d.runs).Sum();
Lather, rinse, repeat:
var joined = from d in deliveries
join players p on d.player_playerid equals p.playerid
join o in overs on d.overid equals o.overid;
where j.o.gameid = 1
select new { p, d, o };
var _runsfor = from j in joined
where j.o.isBatting
&& j.o.gameId == 5
&& j.d.player.playerId == some_player_id
select j;
var ungrouped = from j in joined
select new
{
playerId = j.p.playerid,
runsFor = _runsfor.Where(r => r.p.playerId == j.p.playerId)
.Sum(jn => jn.d.runs),
runsAgainst = //etc...
};
var grouped = from u in ungrouped
group new { u.runsFor, u.runsAgainst, /* etc... */ }
by u.playerId into player
select player;
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.
精彩评论