我正在尝试将SQL查询转换为KnexJS格式,但是当前的KnexJS查询给我以下错误。
这是原始查询,也是我一直在为KnexJS处理的查询。 请更正我的KnexJS查询。 基本上,我想知道如何构建KnexJS查询-内部联接子查询 先感谢您!
原始SQL查询:
pd.date_range("20181101","20181217", freq='W')
更新:
这是对我有用的解决方案:
select DATE_RANGE.START_DATE, DATE_RANGE.END_DATE, count (distinct DATE) as DATE_COUNT
from TASK_HISTORY
join
(select
STORE_ID,
to_number(to_char(to_date(to_char(DATE,'99999999'),'YYYYMMDD') - 1,'YYYYMMDD'),'99999999') as END_DATE
, count (distinct DATE) as REC_COUNT
, to_number(to_char(to_date(to_char(lag (DATE) over (order by DATE asc),'99999999'),'YYYYMMDD') + 1,'YYYYMMDD'),'99999999') as START_DATE
, count (case when FINISH_TIME is not null then 1 end) as COUNT_FINISHED
, count (case when FINISH_TIME is null then 1 end) as COUNT_UNFINISHED
from TASK_HISTORY
where STORE_ID = 43
group by DATE, STORE_ID
having count (case when FINISH_TIME is not null then 1 end) = 0
order by DATE)
as DATE_RANGE
on TASK_HISTORY.DATE >= DATE_RANGE.START_DATE
AND TASK_HISTORY.DATE <= DATE_RANGE.END_DATE
AND TASK_HISTORY.STORE_ID = 43
group by DATE_RANGE.START_DATE, DATE_RANGE.END_DATE, DATE_RANGE.REC_COUNT
order by DATE_COUNT desc, START_DATE desc
答案 0 :(得分:1)
这可能对您有帮助-
const sql = db.table("task_history")
.select('DATE_RANGE.START_DATE', 'DATE_RANGE.END_DATE')
.select(db.raw(`count(distinct DATE) as DATE_COUNT`))
.innerJoin(
db.select('store_id')
.table('task_history')
.select(db.raw(
`to_number(to_char(to_date(to_char(DATE,'99999999'),'YYYYMMDD') - 1,'YYYYMMDD'),'99999999') as END_DATE`
))
.select(db.raw(`count(distinct DATE) as REC_COUNT`))
.select(db.raw(
`to_number(to_char(to_date(to_char(lag (DATE) over (order by DATE asc),'99999999'),'YYYYMMDD') + 1,'YYYYMMDD'),'99999999') as START_DATE`
))
.select(db.raw(`count(case when FINISH_TIME is not null then 1 end) as COUNT_FINISHED`))
.select(db.raw(`count(case when FINISH_TIME is null then 1 end) as COUNT_UNFINISHED`))
.where('store_id', 43)
.groupBy('date', 'store_id')
.having(db.raw(`count(case when FINISH_TIME is not null then 1 end) = 0 order by DATE`))
.as('DATE_RANGE')
, function () {
this.on('DATE_RANGE.START_DATE', '>=', 'TASK_HISTORY.DATE')
.andOn('TASK_HISTORY.DATE', '<=', 'DATE_RANGE.END_DATE')
.andOn('TASK_HISTORY.STORE_ID', 43)
})
.where('task_history.date', '>=', 'DATE_RANGE.START_DATE')
.where('task_history.date', '<=', 'DATE_RANGE.END_DATE')
.groupBy('DATE_RANGE.START_DATE', 'DATE_RANGE.END_DATE', 'DATE_RANGE.REC_COUNT')
.orderBy('DATE_COUNT', 'desc')
.orderBy('START_DATE', 'desc')
.toSQL();
console.log(sql);