2009-08-27 6 views
3

次のクエリをLinq-to-SQLに移動しようとしていますか?linq to sqlにはwith tiesオプションがありますか?

select * from (
Select top (@Percent) percent with ties * 
from(
    Select distinct 
     LoanNumber as LoanNo 
    From CHE 
    Left Join RecordingInfo as Rec 
    On CHE.LoanNumber = Rec.LoanNo 
    Where Channel = 'LINX' 
     and CHE.Doc in ('MTG','MOD') 
     and Rec.LoanNo is null 
     and LoanNumber >= '@LoanNo' 
) A 
order by LoanNo @Order 
) B 
order by LoanNo 

linqの関係とは関係ありません。

答えて

3

私はこれがあなたのために働くと思います。

public static IQueryable<T> TopPercentWithTies<T, TKey>(this IOrderedQueryable<T> query, Expression<Func<T, TKey>> groupByExpression, double percent) 
{ 
    var groupedQuery = query.GroupBy(groupByExpression); 
    int numberToTake = groupedQuery.Count() * percent/100; 
    return groupedQuery.Take(numberToTake).SelectMany(t => t); 
} 

私はIEnumerableでテストしたので、IQueryableで正しく動作するかどうかはわかりません。 TopPercentWithTies()を呼び出す前にリストをソートしました。

これは私がそれをテストするために使用したコードです。

int percent = 50; 
var people = new [] 
{ 
    new { Age = 99, Name = "Adam" }, 
    new { Age = 99, Name = "Andrew" }, 
    new { Age = 89, Name = "Bob" }, 
    new { Age = 50, Name = "Cecil" }, 
    new { Age = 50, Name = "Doug" }, 
    new { Age = 50, Name = "Everett" }, 
    new { Age = 35, Name = "Frank" }, 
    new { Age = 25, Name = "Greg" }, 
    new { Age = 15, Name = "Hank" } 
}; 
var sortedPeople = people.AsQueryable().OrderByDescending(person => person.Age); 
var results = sortedPeople.TopPercentWithTies(person => person.Age, percent); 
foreach (var person in results) 
    Console.WriteLine(person); 

希望するか、少なくとも正しい方向に向けることを望みます。 numberToTakeを計算するためのロジックを調整することができます。

+0

非常にいいです。私はそれがIOrderedQueryableの拡張であると期待しています。 – Maslow

+0

ああ甘い。私はIOrderedQueryableについて知らなかった。私はコードを更新しました。 – Ecyrb

+0

これは、T-SQLの 'TOP n PERCENT WITH TIES'のような結果をもたらさないように見えます。 5050エントリを有するデータ「1 2 2 3 3 3 4 4 4 4 ... 100」を考える。 'TOP 1 PERCENT WITH TIES'は55行(値 '10'まで)を返しますが、関数は1行しか返しません。 –

関連する問題