1

データベースレベルまたはLinqからEFレベルで解決できる次のシナリオがあります。データベースでの私の見解は次のとおりです。

id  title   date           weight
==================================
1   t1     2013-01-18       1.5
1   t1     2013-01-17       1.4
1   t1     2013-01-15       1.31
1   t1     2013-01-12       1.22
2   t2     2013-01-19       2.3
2   t2     2013-01-16       2.1
2   t2     2013-01-07       1.81
2   t2     2013-01-19       1.62

結果として必要なのは、日付ごとに最新の各アイテム(t1とt2)からの1つのレコードです。

したがって、出力は次のようになります。

id  title   date           weight
==================================
1   t1     2013-01-18       1.5
2   t2     2013-01-19       2.3

上で述べたように、データベースレベルまたは(Distinct)を使用したlinqレベルでの回答はどちらも歓迎されます。

私のc#linqの一部:

mylist = (from a in db.myview
join art in db.viewTags on a.id equals art.ArticleID
where (art.TagID == tag.ID)
select a).Distinct().Take(10).ToList();

a.id(ビューのidフィールド)に従ってmyviewとは異なるレコードが必要です

ありがとう

4

2 に答える 2

1

編集-更新ごとにIDで区別したい

記事全文:LinqのDistinctBy(プロパティでDistinctオブジェクトを検索)

以下はMoreLINQライブラリの一部です。

DistinctBy機能を使用する

public static IEnumerable<TSource> DistinctBy<TSource, TKey>
    (this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
{
    HashSet<TKey> seenKeys = new HashSet<TKey>();
    foreach (TSource element in source)
    {
        if (seenKeys.Add(keySelector(element)))
        {
            yield return element;
        }
    }
}

したがって、プロパティだけを使用して個別の値を見つけるにはId、次を使用できます。

mylist = (from a in db.myview
 join art in db.viewTags on a.id equals art.ArticleID
 where (art.TagID == tag.ID)
 select a).DistinctBy(a=>a.Id).Take(10).ToList();

select * from table 
inner join
(select max(date) as date,id from table group by id) d 
on d.id = table.id and d.date= table.date
于 2013-01-22T17:15:04.380 に答える
1

以下は、同じ日付に2つの重みがある場合でも、1行になります。

declare @t table (
    id int,
    title varchar(50),
    date datetime,
    weight decimal(19,4)
)

insert into @t (id, title, date, weight) values
   (1, 't1', '20130118', 1.5),
   (1, 't1', '20130118', 1.6),
   (2, 't2', '20130116', 1.4),
   (2, 't2', '20130115', 1.2)

select
    *
from
    (
        select ROW_NUMBER() over (partition by id order by date desc) rn, * 
        from @t
    ) v
where rn = 1
于 2013-01-22T17:30:42.320 に答える