简体   繁体   English

使用多个连接、SUM 和 group by 将 SQL 转换为 Linq

[英]Convert SQL to Linq with multiple joins , SUM and group by

I am trying to convert an SQL query to LINQ where the query has 2 left joins and group by.我正在尝试将 SQL 查询转换为 LINQ,其中查询有 2 个左连接和分组依据。

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这是有效的 SQL 查询,您可以在下面看到我尝试过但无效的 LINQ 代码

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:来自 SQL 查询的样本 output 数据为:

在此处输入图像描述

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:这个应该可以工作,它不是 FULL OUTER JOIN 但是,我认为,使用您的数据它可能会工作:

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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM