2017-06-19 110 views
0

如何將此SQL查詢轉換爲Entity Framework v4.0查詢?如何將此SQL查詢轉換爲Entity Framework v4.0查詢?

WITH Sales_CTE (Name, Count1) AS 
(
    SELECT TOP 1000000 
     Name, COUNT(Name) 
    FROM 
     Customers 
    WHERE 
     subscriptionState != 0 
    GROUP BY 
     Name 
    HAVING 
     COUNT(Name) >= 0 
    ORDER BY 
     COUNT(Name) 
) 
SELECT 
    COUNT(count1), Count1 
FROM 
    Sales_CTE 
GROUP BY 
    count1 

回答

0

像這樣的東西在EF6:

 var sales_cte = from c in db.Customers 
         where c.subscriptionState != 0 
         group c by c.Name into c_byName 
         where c_byName.Count() > 0 
         orderby c_byName.Count() 
         select new { Name = c_byName.Key, Count1 = c_byName.Count() }; 

     var q = from r in sales_cte.Take(1000000) 
       group r by r.Count1 into r_byCount1 
       select new { Count = r_byCount1.Count(), Count1=r_byCount1.Key }; 

轉化爲

SELECT 
    1 AS [C1], 
    [GroupBy2].[A1] AS [C2], 
    [GroupBy2].[K1] AS [C3] 
    FROM (SELECT 
     [Limit1].[A3] AS [K1], 
     COUNT(1) AS [A1] 
     FROM (SELECT TOP (1000000) [GroupBy1].[A3] AS [A3] 
      FROM (SELECT 
       [Extent1].[Name] AS [K1], 
       COUNT(1) AS [A1], 
       COUNT(1) AS [A2], 
       COUNT(1) AS [A3] 
       FROM [dbo].[Customers] AS [Extent1] 
       WHERE 0 <> [Extent1].[subscriptionState] 
       GROUP BY [Extent1].[Name] 
      ) AS [GroupBy1] 
      WHERE [GroupBy1].[A1] > 0 
      ORDER BY [GroupBy1].[A2] ASC 
     ) AS [Limit1] 
     GROUP BY [Limit1].[A3] 
    ) AS [GroupBy2]