简体   繁体   中英

c# Lambda subqueries (linq2sql)

Is it possible to write the equivalent of this TSQL statement in Lambda?

SELECT  DISTINCT
        pba1.adGroupsId
,      Amount = (SELECT pba2.value 
                  FROM   ProjectBudgetAdjustment pba2 
                  WHERE  pba1.budgetId = pba2.budgetId 
                  AND    pba1.adGroupsId = pba2.adGroupsId 
                  AND    pba2.metricId IN 
                  (
                      SELECT  id 
                      FROM    Metrics 
                      WHERE   [description] = 'Amount')
                  )
,      [Hours] = (SELECT pba2.value 
                   FROM   ProjectBudgetAdjustment pba2 
                   WHERE  pba1.budgetId = pba2.budgetId 
                   AND    pba1.adGroupsId = pba2.adGroupsId 
                   AND    pba2.metricId IN 
                  (
                      SELECT id 
                      FROM   Metrics 
                      WHERE  [description] = 'Hours')
                  )
FROM    ProjectBudgetAdjustment pba1
WHERE   pba1.budgetId IN
(
   SELECT  id
   FROM ProjectBudget
   WHERE   projectId IN
   (
      SELECT  id
      FROM    Projects
      WHERE   code = 'xxx'
   )
)

I could be total wrong here, but is it something like :

ProjectBudgetAdjustment
.Where( pba => pba.ProductBudget.Products.Code == "xxx")
.Where( pba => (pba.Metrics.Description == "Hours" 
             || pba.Metrics.Description == "Amount"))
.GroupBy(   pba => pba.ProductBudget.adGroupsId )
.Select (
    r => new
    {
        adGroupsId = r.Key,
        Hours  = r.Sum(i=> (i.Metrics.Description == "Hours"  ? i.value : 0m)),
        Amount = r.Sum(i=> (i.Metrics.Description == "Amount" ? i.value : 0m))
    }
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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