选择基于计数

时间:2015-03-07 00:16:22

标签: linq entity-framework linq-to-entities

我有一张桌子比尔。

此表格包含字段Id_Client

我想恢复一个超过一些账单的客户列表。

在SQL中,我做了类似的事情

select Id_Client, Count(*)
from MyDB.dbo.Bill
group by Id_Client
having Count(*) > 100
order by c desc

其中100是此限制的一个示例。

我想在实体框架中执行此操作 - LINQ。

1 个答案:

答案 0 :(得分:0)

试试这个:

var query= db.Bills.GroupBy(b => b.Id_Client)
                   .Select(g => new {Id_Client = g.Key, Count = g.Count()})
                   .Where(r => r.Count > 100)
                   .OrderByDescending(r=>r.Count);

此Linq查询将在sql:

中转换为此查询
{SELECT 
[GroupBy1].[K1] AS [Id_Client], 
[GroupBy1].[A1] AS [C1]
FROM ( SELECT 
    [Extent1].[Id_Client] AS [K1], 
    COUNT(1) AS [A1]
    FROM [dbo].[Bill] AS [Extent1]
    GROUP BY [Extent1].[Id_Client]
)  AS [GroupBy1]
WHERE [GroupBy1].[A1] > 100
ORDER BY [GroupBy1].[A1] DESC}