簡體   English   中英

SQL to LINQ語句,包括分組依據和排序依據

[英]SQL to LINQ Statement including Group By and Order By

我在下面有一個SQL查詢:

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

我試圖將其轉換為ASPX.CS代碼后面的LINQ查詢,以填充表並在圖表中使用數據。

我到目前為止有以下內容:

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(); 

這只是表2部分。 我也試圖加入表1,並且仍然從我無法獲取的代碼中獲取費用的計數。 我發現有幾個帖子和解決方案可以單獨完成每個任務,但在獲得列數時卻沒有按分組和加入的答案。 誰能將我引導到可以幫助或指導我正確方向的資源?

我想到了這一點(可能需要進行一些調整)

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();

嘗試這樣的事情:

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(); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM