@gfrizzle pointed out here that LINQ to SQL generates independent SELECT statements for each count operation when given LINQ like this:
From d in db
Group d.a.AuditStatus By d.a.DateCreated Into Group
Select _
DateIssued = DateCreated, _
TotalAudits = Group.Count(), _
TotalCancelled = Group.Count(Function(x) If(x = "Cancelled", True, False)), _
TotalComplete = Group.Count(Function(x) If(x = "Complete", True, False)), _
TotalIssued = Group.Count(Function(x) If(x = "Issued", True, False)), _
TotalPending = Group.Count(Function(x) If (x = "Pending", True, False)), _
Remaining = 0
As the data in question gets large enough, this could easily result in a huge performance hit. I know I could rewrite this as a native SQL query, but I’m using several features of LINQ in other places (like the ability to break my where clause up) that I don’t want to give up if I can avoid it. Any other workarounds?
Eureka! I finally got it. It’s a logical problem in the way the underlying SQL is constructed. There is no way to write that LINQ as a single pass SQL query because COUNT operations only look at the number of rows regardless of any WHERE style clause.
The solution is to mimic a COUNT/WHERE combination by using SUM instead. This LINQ query creates a single pass SQL query using SUM(CASE WHEN) columns.