sql - 如何将SELECT DISTINCT ON转换为knex.js

标签 sql postgresql knex.js

我很难把DISTINCT ON子句翻译成knex.js
在join()中使用多个andOn的过程中也可能会出现一些错误。
找不到正确翻译的方法。

select DISTINCT ON (f1.operdate) f1.operdate as date,
  f2.operdate as opendate,
  opercodes.naenter code hereme as name,
  f1.person as person,
  f1.comments as comments,
  f2.person as conductor    
from cashboxdiary as f1
inner join opercodes on (opercodes.id = f1.opercode)
inner join cashboxdiary f2 on (f2.company = f1.company and f2.cashbox = f1.cashbox and f2.opercode = 3 and f2.operdate < f1.operdate)

我到目前为止所做的努力
knex("cashboxdiary")
.innerJoin("opercodes", "opercodes.id", "cashboxdiary.opercode")
.join('cashboxdiary as f2',function () {
    this.on('f2.company','=','cashboxdiary.company')
    .andOn('f2.cashbox','=','cashboxdiary.cashbox')
    .andOn('f2.opercode','=',knex.raw('?',[3]))
    .andOn('f2.operdate','<','cashboxdiary.operdate');      
})
.where({ "cashboxdiary.company": company, "cashboxdiary.cashbox": cashbox})
.whereNotIn("cashboxdiary.opercode", [3, 4, 5, 6])
.andWhereBetween(knex.raw("cashboxdiary.operdate::date"), [
  dateFrom.format(),
  dateTo.format()
])
.select(knex.raw('distinct on (cashboxdiary.operdate) cashboxdiary.operdate as date,f2.operdate as opendate, opercode.name as name, cashboxdiary.person as person, cashboxdiary.comments as comments, f2.person as conductor'))

最佳答案

是语法错误。应该这样写选择:
.select(knex.raw('distinct on(cashboxdiary.operdate) cashboxdiary.operdate as date'),'f2.operdate as opendate', 'opercode.name',...)

关于sql - 如何将SELECT DISTINCT ON转换为knex.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58410882/

相关文章:

java - SQLServer 异常 : Invalid column name

php - 使用 PHP 移动 MySQL 行

sql - "on"处或附近的语法错误

mysql - 尝试使用 knex 并在 where 子句中嵌入 select 来构建复杂查询

mysql - SQL元表帮助(mysql)

php - 自定义表 WordPress 上的查询

python - Python 和 Postgres 语言环境货币格式之间的区别

SQL在多个条件下按月和年带来结果

node.js - 从数据库/文件夹运行 knexfile.js

node.js - 尝试 knex 种子 :run after successful knex migrate:latest for remote database 时出错