Hello,
Not sure if this is just a bad habit, or a valid way of doing things, but for large complex report queries spanning bunches of tables, I often get my aggregate stats by summing a Case
statement.
For example:
SELECT Contact.Name,
SUM(CASE WHEN Order.Type = 'Special' THEN 1 ELSE 0 END) AS SpecialOrders,
SUM(CASE WHEN Order.Type = 'Magic' THEN 1 ELSE 0 END) AS MagicOrders,
FROM Contact
LEFT JOIN Order ON (Contact.ContactID = Order.ContactID)
How would I do this in LINQ to SQL? (In vb.net, but I guess any .Net example would do)
Dim Orders = _
From Order In DB.Orders
Select New With {.Name = Contact.Name,
.Special = If(Order.Type = "Special", 1, 0),
.Magical = If(Order.Type = "Magical ", 1, 0)}
I need to sum the .Special
and .Magical
values.
(In reality, the query spans several tables consisting of event-booking information, and the decision to sum a record or not depends on fields in several of them)