Join with Count?

Discussion of open issues, suggestions and bugs regarding LinqConnect – Devart's LINQ to SQL compatible ORM
Post Reply
bgwalker
Posts: 2
Joined: Sat 27 Mar 2010 03:36

Join with Count?

Post by bgwalker » Sat 27 Mar 2010 03:39

Good evening...

I'm relatively new to LINQ and am trying to figure out how to do a percentage calculation using Count() on a join. My original SQL query looks like this:
SELECT
c.[ID], c.

Code: Select all

,
     ISNULL(p.[ActualTotalCount],0) AS ActualTotalCount,
     ISNULL(p.[CodeTotalCount],0) AS CodeTotalCount,
     CAST(ISNULL(p.[CompletionPercentage],0) AS Integer) AS CompletionPercentage
FROM deployment_codes AS c
     LEFT OUTER JOIN
          (SELECT
               [CodeID],
               ISNULL(COUNT([Actual]),0) As ActualTotalCount,
               ISNULL(COUNT([CodeID]),0) As CodeTotalCount,
               (CAST(ISNULL(COUNT([Actual]),0) AS Float) / CAST(ISNULL(COUNT([CodeID]),1) AS Float))*100 AS CompletionPercentage
          FROM
               deployment_plan
          WHERE [Group] = 'LA'
          GROUP BY 
               [CodeID]) AS p
          ON c.[ID] = p.[CodeID]
WHERE (c.[code] LIKE 'N%')
[/quote]
Last edited by bgwalker on Sat 27 Mar 2010 03:42, edited 2 times in total.

bgwalker
Posts: 2
Joined: Sat 27 Mar 2010 03:36

Post by bgwalker » Sat 27 Mar 2010 03:41

After playing around in LINQPad, I've come up with the following LINQ to SQL:

Code: Select all

From c In deployment_codes _
Group Join p In deployment_plans.Where(Function(g) g.Group = "LA") on c.ID Equals p.CodeID _
Into CodePlan = Group _
Where (c.Code.StartsWith("N")) _
Select c.ID, c.Code, TotalCount = CodePlan.Count
I can get the "CodeTotalCount" by doing a "CodePlan.Count", but now I need the "ActualTotalCount", which is a count of non null items in the "Actual" column in "deployment_plans". After I get the count, I need to do some math to figure out the percentage (("ActualTotalCount" / "TotalCount") * 100) with avoiding a "divide by zero" error.

Please help! :)

AndreyR
Devart Team
Posts: 2919
Joined: Mon 07 Jul 2008 13:16

Post by AndreyR » Thu 01 Apr 2010 09:49

A simpler solution is to use the DataContext.ExecuteQuery method to send a SQL query directly to database.

Post Reply