使用OrderBy和GroupBy从SQL创建Linq

时间:2015-12-25 09:53:14

标签: c# sql sql-server linq linq-to-sql

我有以下表结构。

TableA      TableB          TableC
- MID       - PID           - PID
- NAME      - INIT_DATE     - MID

这是我需要转换为Linq的SQL查询

SELECT TOP 10 TableA.NAME, 
               COUNT(TableB.INIT_DATE) AS [TOTALCOUNT]
FROM TableC 
INNER JOIN TableA ON TableC.MID = TableA.MID 
LEFT OUTER JOIN TableB ON TableC.PID = TableB.PID
GROUP BY TableA.NAME
ORDER BY [TOTALCOUNT] DESC

我尝试使用此Linq查询重现上述查询:

iqModel = (from tableC in DB.TableC
           join tableA in DB.TableA on tableC.MID equals tableA.MID
           select new { tableC, tableA } into TM
           join tableB in DB.TableB on TM.tableC.PID equals J.PID into TJ
           from D in TJ.DefaultIfEmpty()
           select new { TM, D } into MD
           group MD by MD.TM.tableA.NAME into results
           let TOTALCOUNT = results.Select(item=>item.D.INIT_DATE).Count()
           orderby TOTALCOUNT descending
           select new SelectListItem
           {
               Text = results.Key.ToString(),
               Value = TOTALCOUNT.ToString()
            }).Take(10);

但我认为我做错了。

LINQ和SQL的输出不一样。我认为JOIN或GROUPBY是正确的。

编辑: -

我也尝试了以下Linq查询,但仍然无法正常工作。

var iqModel = (from c in DB.TableC
               join a in DB.TableA on c.MID equals a.MID
               join b in DB.b on c.PID equals b.PID into b_join
               from b in b_join.DefaultIfEmpty()
               select new SelectListItem { Text = a.NAME, Value = b.INIT_DATE != null ? b.INIT_DATE.ToString() : string.Empty });

var igModel = iqModel.GroupBy(item => item.Text);

var result = igModel.OrderByDescending(item => item.Select(r => r.Value).Count());

我想了解我做错了什么以及如何解决。

我是LINQ to SQL的新手我认为在上面的LINQ中我真的通过添加更多选择使它变得复杂。

2 个答案:

答案 0 :(得分:1)

我认为差异是因为SQL COUNT(field)函数不包含NULL值。在LINQ中没有直接的等效构造,但它可以用Count(e => e.Field != null)或类似的模拟(这似乎产生更好的SQL):

var query = 
    (from a in db.TableA
     join c in db.TableC on a.MID equals c.MID
     join b in db.TableB on c.PID equals b.PID into joinB
     from b in joinB.DefaultIfEmpty()
     group b by a.Name into g
     let TOTALCOUNT = g.Sum(e => e.INIT_DATE != null ? 1 : 0)
     orderby TOTALCOUNT descending
     select new SelectListItem { Text = g.Key, Value = TOTALCOUNT }
    ).Take(10);

生成以下SQL

SELECT TOP (10) 
    [Project1].[C2] AS [C1], 
    [Project1].[Name] AS [Name], 
    [Project1].[C1] AS [C2]
    FROM ( SELECT 
        [GroupBy1].[A1] AS [C1], 
        [GroupBy1].[K1] AS [Name], 
        1 AS [C2]
        FROM ( SELECT 
            [Join2].[K1] AS [K1], 
            SUM([Join2].[A1]) AS [A1]
            FROM ( SELECT 
                [Extent1].[Name] AS [K1], 
                CASE WHEN ([Extent3].[INIT_DATE] IS NOT NULL) THEN 1 ELSE 0 END AS [A1]
                FROM   [dbo].[TableAs] AS [Extent1]
                INNER JOIN [dbo].[TableCs] AS [Extent2] ON [Extent1].[MID] = [Extent2].[MID]
                LEFT OUTER JOIN [dbo].[TableBs] AS [Extent3] ON [Extent2].[PID] = [Extent3].[PID]
            )  AS [Join2]
            GROUP BY [K1]
        )  AS [GroupBy1]
    )  AS [Project1]
    ORDER BY [Project1].[C1] DESC

答案 1 :(得分:0)

我假设您在结果查询中未看到“ group by ”命令,而不是使用“ distinct ”命令。我是对的吗?

第一个查询使用TableA.NAME进行区分,然后在子查询的帮助下计算COUNT(TableB.INIT_DATE),如下所示:

select distinct1.Name, (select count() from *join query* where Name = distinct1.Name)
from (select distinct Name from *join query*) as distinct1

如果是这样,不用担心。因为从linq到真正的t-sql脚本的转换有时非常不可预测(你不能强迫它们相等,只有当查询非常简单时),但是两个查询彼此相同并返回相同的结果(比较它们以确保)