database - F# 查询 : find rows with max value in each group

标签 database f# entity-framework-core computation-expression

在我的项目中我使用:

  • F# 查询工作流
  • Entity Framework 核心 3.11
  • MS SQL

我有一个与此类似的问题:SQL select only rows with max value on a column,但我想知道如何使用 F# 查询工作流表达该问题中出现的 SQL:

SELECT a.id, a.rev, a.contents
FROM YourTable a
INNER JOIN (
    SELECT id, MAX(rev) rev
    FROM YourTable
    GROUP BY id
) b ON a.id = b.id AND a.rev = b.rev

最佳答案

直接翻译

对于直接翻译,内部查询是:

let innerQuery =
    query {
        for inner in ctx.YourTable do
        groupBy inner.id into grp
        select (grp.Key, grp.Max(fun ent -> ent.rev))
    }

然后,理论上,我认为完整的查询应该是:

query {
    for outer in ctx.YourTable do
    join inner in innerQuery
        on ((outer.id, outer.rev) = inner)
    select outer
}

但是,这不起作用:

Type mismatch when building 'ty': function type doesn't match delegate type. Expected

'Microsoft.FSharp.Core.FSharpFunc`2[Program+YourTable,System.Tuple`2[System.Int32,System.Int32]]'

, but received type

'Microsoft.FSharp.Core.FSharpFunc`2[Program+YourTable,Microsoft.FSharp.Linq.RuntimeHelpers.AnonymousObject`2[System.Int32,System.Int32]]'.

我可能是错的,也可能是错误/限制。也许有人有解决方法。

替代翻译

但是,如果您接受略有不同的翻译,它确实有效:

query {
    for outer in ctx.YourTable do
    where (
        query {
            for inner in ctx.YourTable do
            groupBy inner.id into grp
            exists (grp.Key = outer.id && grp.Max(fun ent -> ent.rev) = outer.rev)
        })
    select outer
}

生成的 SQL 是:

SELECT [y].[id], [y].[rev], [y].[contents]
FROM [YourTable] AS [y]
WHERE EXISTS (
    SELECT 1
    FROM [YourTable] AS [y0]
    GROUP BY [y0].[id]
    HAVING ([y0].[id] = [y].[id]) AND (MAX([y0].[rev]) = [y].[rev]))

输出是:

{ id = 2
  rev = 1
  contents = "..." }
{ id = 1
  rev = 3
  contents = "..." }

请注意,在构建模型时,我必须设置 id, rev 的复合主键:

override __.OnModelCreating(modelBuilder: ModelBuilder) =
    modelBuilder.Entity<YourTable>()
        .HasKey([| "id"; "rev" |]) |> ignore

完整代码是 here .

关于database - F# 查询 : find rows with max value in each group,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69270982/

相关文章:

php - 数据库查询未按预期运行

php - html 表单数据未使用 PHP 和 PDO 插入 MySQL 数据库

visual-studio - 转到 F# 库的定义

asp.net - IServiceCollection 不包含 AddNpgsql 的定义或扩展

entity-framework-core - EF Core - 为什么 ClientSetNull 是可选关系的默认 OnDelete 行为(而不是 SetNull)

c# - 事务 Rollback() 是否有机会抛出异常?

php - 带有 ACL 的 MySQL DB 的 Rest 接口(interface)

javascript - 使用javascript读写sqlite数据库

f# - 如何在 F# 中对顺序值进行分组

c# - 即使 Process.HasExited 为真,Process.WaitForExit 也不会返回