Justin
Justin

Reputation: 35

SQL to LINQ Statement including Group By and Order By

I have an SQL query below:

SELECT DISTINCT 
    Table1.Description, 
    Table2.AccountId, 
    COUNT(Table2.AccountId) AS Charges 
FROM Table2 
LEFT JOIN Table1 ON Table2.AccountId = Table1.Id 
WHERE Table2.DateTime > '3/1/2014' 
    AND Table2.DateTime < '4/1/2014' 
GROUP BY Table2.AccountId, Table1.Description 
ORDER BY Charges DESC

I am trying to convert this to a LINQ query in the ASPX.CS code behind to populate a table and to use the data in a chart.

What I have so far is below:

var resultList = configDB.Table2
    .Where(x => x.DateTime > begDate && x.DateTime < endDate)
    .GroupBy(x => x.AccountID)
    .Select(g => new { Account = g.Key, Charges = g.Count() })
    .OrderByDescending(g => g.Charges)
    .ToList(); 

This is only the Table 2 portion. I'm trying to join Table 1 as well and still get the count of Charges which from toying around with the code I was unable to get. I've found several posts and solutions to do each one individually but not an answer where they are grouping by and joining while getting a count of a column. Can anyone direct me to a resource that will help or point me in the right direction?

Upvotes: 1

Views: 1117

Answers (2)

Oleksii Aza
Oleksii Aza

Reputation: 5398

Try something like this:

var resultList = configDB.Table2
                        .Where(x => x.DateTime > begDate && x.DateTime < endDate)
                        .GroupJoin(configDB.Table1,
                                    t2 => t2.AccountId,
                                    t1 => t1.Id,
                                    (t2, joined) => new
                                    {
                                        Description = joined.Select(t => t.Description).FirstOrDefault(),
                                        AccountID = t2.AccountId,
                                    })
                        .GroupBy(x => x.AccountID)
                        .Select(g => new
                        {
                            Account = g.Key, 
                            Charges = g.Count(), 
                            Description = g.Select(d=>d.Description).FirstOrDefault()
                        })
                        .OrderByDescending(g => g.Charges)
                        .ToList(); 

Upvotes: 0

Dennis_E
Dennis_E

Reputation: 8904

I came up with this (might need some tweaking)

var resultList = Table2
            .Where(x => x.DateTime > begDate && x.DateTime < endDate)
            .Join(Table1, t2 => t2.AccountId, t1 => t1.Id,
                (t2, t1) => new { t2.AccountId, t1.Description })
            .GroupBy(x => x.AccountId)
            .Select(g => new { Group = g, Charges = g.Count() })
            .OrderByDescending(g => g.Charges)
            .SelectMany(g => g.Group.Select(x => new { x.Description, x.AccountId, g.Charges }))
            .ToList();

Upvotes: 1

Related Questions