Linq to SQL 嵌套选择组(按计数)

标签 linq count group-by nested having

我需要将查询从 sql 转换为 linq 创建表历史记录

CREATE TABLE [dbo].[History](
    [HistoryID] [int] IDENTITY(1,1) NOT NULL,
    [AuctionID] [int] NOT NULL,
    [UserName] [nvarchar](128) NULL,
    [Time] [datetime] NOT NULL,
    [Price] [decimal](18, 2) NOT NULL,
)

查询

select [UserName],[Price] from [History] 
where [Price] in 
    (SELECT [Price] FROM [History]  
    where ID=28 GROUP BY [Price]
    HAVING COUNT(*)=1) 
        Order by [Price]

最佳答案

我认为您正在寻找与您的 SP 类似的 LINQ 语句。使用下面的一个

// Using Plain LINQ statements
var result1 = from history in lstHistory
              where history.ID == 28
              group history by history.Price into g
              orderby g.Key
              where g.Count() == 1
              select new 
                { 
                    Price = g.Key, 
                    UserName = g.Select(h => h.UserName).FirstOrDefault() 
                };

或者

// Using Lambda Expressions
var result2 = lstHistory
                .Where(q => q.ID == 28)
                .OrderBy(t => t.Price)
                .GroupBy(h => h.Price)
                .Where(grp => grp.Count() == 1)
                .Select(g => new 
                           { 
                              Price = g.Key, 
                              UserName = g.Select(h => h.UserName).FirstOrDefault() 
                            });

关于Linq to SQL 嵌套选择组(按计数),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13238087/

相关文章:

r - 计算向量中不同值的数量

MySQL 错误 : Non-grouping field is used in HAVING clause

c# - LINQPad,使用多个数据上下文

c# - 无法从票证集合中选择最新的票证

c# - IEnumerable<T>.包含谓词

group-by - Pyspark groupby 然后在组内排序

mysql - 通过在一个简单的表上使用 MySql 进行三次计数和分组......是否可以在一个查询中进行?

c# - 检查实体是否实现接口(interface)并在通用存储库中添加谓词

sql - 如何将选择表达式的结果保存为变量?

Mysqli PHP 查询计数