簡體   English   中英

使用LINQ按最新日期獲取所有記錄(從單個表中獲取)

[英]Get all records (from single table) by latest date using LINQ

我正在嘗試使用LINQ在最新日期之前獲取所有記錄(從單個表中獲取),但是有一些問題。 例如,如果表中有兩行具有最新日期,那么我需要根據特定條件來獲取這兩行。 請幫忙

這是我的代碼。

var q = (from n in Table
         where n.CustomerId == customerId && n.Isactive==true
         group n by new { n.CustomerId, n.ConsentId } into grp
         select new
         {
            // select all fields
            grp.Key.ConsentId,
            grp.Key.CustomerId,
            Date = grp.Max(t=>t.CreatedOn)
         }).ToList(); 

您必須將CustomerId+ConsentId -group分成一個子組(通過CreatedOn ):

var q = Table
    .Where(x => x.CustomerId == customerId && x.Isactive)
    .GroupBy(x => new { x.CustomerId, x.ConsentId })
    .SelectMany(g => g
        .GroupBy(x => x.CreatedOn.Date).OrderByDescending(x => x.Key).First()
        .Select(x => new
        {
            g.Key.ConsentId,
            g.Key.CustomerId,
            Date = x.CreatedOn // this is the max-date per group
        }));

據我了解,您需要來自Table的所有記錄,這些記錄屬於具有特定ID( CustomerId = <id> )的active( IsActive = true )客戶,並且該記錄必須是最新的( max(CreatedOn) )。 我不明白什么是ConsentId,您是否真的需要它。 您已經完成了一半的解決方案,您已經為該客戶獲得了max(CreatedOn)值。 現在,您只需要從表中為此客戶選擇行,並且CreatedOn = founded max

var q1 = from n in Table
            join max in (from n1 in Table
                        where n1.CustomerId == customerId && n1.Isactive==true
                        group n1 by new { n1.CustomerId, n1.ConsentId }
                        into grp
                        select new { grp.Key.CustomerId, grp.Key.ConsentId, MaxCreatedOnDate = grp.Max(r => r.CreatedOn) }) 
            on new { CustomerId = n.CustomerId, ConsentId = n.ConsentId, date = n.CreatedOn } equals new { CustomerId = max.CustomerId, ConsentId = max.ConsentId, date = max.MaxCreatedOnDate }
            select n;

UPD。 如果表中有多個組(CustomerId,ConsentId),則內部查詢(它是您的查詢)可以提供多於1行。 如果只需要按CustomerId分組,則刪除查詢中所有ConsentId外觀。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM