2014-03-19 39 views
4

我必须从表中提供具有特定单词的文档,并且必须使用order,以便具有最高计数的那些文档首先出现。例如根据口述组计数排序

文件1:这是一所学校。这是我校
文献2:这是我们学校的
文献3:我校是这这这

现在,如果我用

select Document.Id, Document_Word.Location from Document, Document_Word, word where Document.Id = Document_Word.Document_Id and Document_Word.Word_Id = Word.Id and Word.Word = 'this'

Reault是
result

我想通过降序排序的唯一ID的计数...我其实需要LINQ查询这个问题

这是我的数据库架构

Schema

希望我说我的问题清楚......

回答

2

下面是使用实体框架的样品,在`g.Count(X => x.Id)

using (var context = new MyDbContext()) 
{ 
    var documentEntities = (from document in context.Documents 
     join document_word in context.Document_Word on document equals document_word.Document 
     join word in context.Words on document_word.Word equals word 
     where word.Word1 == "this" // Filter for word = "this" 
     group document_word by document_word.Document.Id into documentWordGroup // First group Document_Words by document Id so that we can sort based on the Id count 
     let IdCount = documentWordGroup.Count() // store the count into a variable IdCount 
     orderby IdCount descending // here we sort by the IdCount 
     select documentWordGroup).ToArray() // select the sorted Document_Word groups 
     .SelectMany(dw => dw); // combine the groups into a single array of Document_Words 

    //Display the result in the Console output 
    Console.WriteLine("ID" + "\t" + "Location"); 
    foreach (var document in documentEntities) 
    { 
     Console.WriteLine(document.Document.Id + "\t" + document.Location); 
    } 
} 
+0

感谢它的完美....我会写SQL语句,并试图在LINQ中转换它, 保持祝福 –

+0

感谢您的确认...很高兴知道它的工作为你 :-) –

1

这里是一个LINQ查询。

var res = (from document in Documents 
    join document_word in DocumentWords on document.Id equals document_word.Document_Id 
    join word in Words on document_word.WordId equals word.wordId 
    group document by document.Id 
    into g 
    let IdCount = g.Count() 
    orderby IdCount descending 
    select new {Key = g.Key, Items = g.Distinct().ToList()}). 
    SelectMany(x => x.Items).ToList(); 

这个按文件ID分组,并做降序排序并返回组。 希望这对你有所帮助。

+0

烨错误'它说不能隐式转换型'int'到'bool' –

+0

我编辑了答案 –

+0

LINQ to Entities无法识别方法'System.Collections.Generic.List'1 [Search_Engine.Models.Document] ToList [Document](System.Collections.Generic.IEnumerable'1 [Search_Engine.Models。 Document])方法,并且此方法不能转换为商店表达式。 –

0

也许SQL查询将是对你或其他人(也许你可以把它翻译成LINQ)

首先,我们需要数(ID)的帮助。让我们找到它:

SELECT *,count(ID) FROM document GROUP BY ID order by count(ID) 

然后,我们可以内部联接上面的表格与文件:

SELECT * FROM document 
INNER JOIN (SELECT *,count(ID) FROM document GROUP BY ID order by count(ID)) y 
ON document.ID=y.ID 

该代码将返回不同的地点数量排序ID。

+1

不...它说** ORDER BY子句在视图中无效** –

+0

好吧,也许尝试没有ORDER BY并看到结果?然后当你执行这个视图时,你可以把count(ID)写成count和count by desc。 – user3162968

+0

如果我们使用group by子句,那么重复条件成为一个单位..这不需要...例如在这种情况下,我只得到(id - count)(1 ---- 2)(2 --- -1)(3 ---- 3) –