开发者

SQL to LINQ simple query?

开发者 https://www.devze.com 2023-01-08 12:20 出处:网络
below is a sql server table, which is used to hold users prediction for soccer matches. a user can predict either a home win, an away win or a draw/tie for a specific soccer match.

below is a sql server table, which is used to hold users prediction for soccer matches. a user can predict either a home win, an away win or a draw/tie for a specific soccer match.

how开发者_如何学C can i query this table to find the top 3 predictions, the top 3 games must be distinct gameId's

either SQL or LINQ solution would be much appriciated

alt text http://preview.robson-brown.com/capture.png


I'll assume you want the strongest predictions, i.e., the games where the most people agree on the outcome.

 var predictions = db.Predictions
                     .GroupBy( g => g.gameId )
                     .Select( g => new 
                      {
                            gameId = g.Key,
                            homeWin = g.Sum( h => h.homeWin ),
                            awayWin = g.Sum( a => a.awayWin ),
                            draw = g.Sum( d => d.draw )
                      })
                     .Select( g => new 
                      {
                            gameId = g.gameId,
                            prediction = g.homeWin > g.awayWin 
                                             ? (g.homeWin > draw 
                                                    ? 'homeWin'
                                                    : 'draw')
                                             : (g.awayWin > g.draw
                                                    ? 'awayWin'
                                                    : 'draw'),
                            strength = g.homeWin > g.awayWin 
                                             ? (g.homeWin > draw 
                                                    ? g.homeWin
                                                    : g.draw) 
                                             : (g.awayWin > g.draw 
                                                    ? g.awayWin 
                                                    : g.draw)
                      })
                     .OrderByDescending( g => g.strength )
                     .Take(3);

You might be able to combine the two selects, but IMO it would hurt the readability of the code.

0

精彩评论

暂无评论...
验证码 换一张
取 消