views:

342

answers:

1

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)

+1  A: 
var specialSum = DB.Orders.Sum (o => o.Type == "Special" ? 1 : 0)
var magicalSum = DB.Orders.Sum (o => o.Type == "Magical" ? 1 : 0)

Or:

var specialSum = DB.Orders.Count (o => o.Type == "Special")
var magicalSum = DB.Orders.Count (o => o.Type == "Magical")
Developer Art
That's C#, OP is looking for the VB.Net equivalent.
JaredPar
"In vb.net, but I guess any .Net example would do" - that's what he said. I'm afraid I don't speak VB.
Developer Art