繁体   English   中英

使用Lambda表达式从SQl获取唯一行

[英]Getting Unique rows from SQl using Lambda Expression

我有下面的表结构。 我试图弄清楚如何使用TransactionId列获取唯一行的总数。

表结构

有些人可以帮助我如何使用TransactionId列获取唯一行。

提前致谢!

select count(distinct case when right(transactionid, 2) like '-[0-9]'
                      then left(transactionid, len(transactionid) - 2) --cut out the version (-1,-2,-3,etc.)
                      else transactionid end
        ) [NumberOfUniqueTransactionId]
from MY_TABLE

您必须使用不同的

 select distinct  left(TransactionId,LEN(TransactionId)-CHARINDEX('-',TransactionId)) from yourTable

假设您使用Linq To SQL或实体框架查询SQL(假设因为您提到了有关使用C#lambda表达式的信息)

假设您的poco实体看起来像:

public class Entity
    {
        public string TransactionId { get; set; }
        public string ServiceId { get; set; }
        public string SourceApplicationName { get; set; }
    }

您可以使用以下查询:

List<Entity> entities = null; /* you might want to use it from DB context */
var result = entities.DistinctBy(e => new { e.TransactionId, e.ServiceId, e.SourceApplicationName });

由于DistinctBy无法用作扩展方法。 您可以使用一种通用的扩展方法,如下所示:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM