【发布时间】:2021-03-11 00:00:38
【问题描述】:
此 MS SQL 查询通过查询排除周末和节假日的日历表,返回距给定开始日期(21 年 3 月 1 日)189 个工作日后的结束日期。这是基本的 SQL 查询:
select Top 1 TheDate as EndDate
FROM (select Top 189 d.TheDate from DateDimension d
LEFT JOIN USHolidayDimension h
ON d.TheDate = h.TheDate
where d.TheDate>='03/01/2021'
and IsWeekend=0 and H.TheDate is null
order by d.TheDate) as BusinessDays
order by TheDate DESC
此查询正确返回 21 年 11 月 24 日的日期,即从 21 年 3 月 1 日起的 189 个工作日。
我尝试了几种在 QueryBuilder 中编写它的方法,但一直收到错误 Cannot build query because main alias is not set (call qb#from method)"
这是我的第一个查询:
const endDate = await getConnection()
.createQueryBuilder()
.select("select Top 1 TheDate as EndDate " +
"FROM (select Top 189 d.TheDate from DateDimension d" +
"LEFT JOIN USHolidayDimension h " +
"ON d.TheDate = h.TheDate " +
"where d.TheDate>='03/01/2021'" +
"and IsWeekend=0 and H.TheDate is null "+
"order by d.TheDate) as BusinessDays " +
"order by TheDate DESC")
.getRawMany();
这是我的第二次尝试 - 相同的错误消息:
const endDate = await connection .createQueryBuilder() .select("Top 1 TheDate", "Top1")
.addSelect(subQuery => {
return subQuery
.select("Top 189 d.TheDate")
.from("DateDimension", "d")
.leftJoinAndSelect("USHolidayDimension", "h", "d.TheDate = h.TheDate")
.where( "d.TheDate>='03/01/2021'")
.andWhere("IsWeekend=0 and H.TheDate is null")
}, "businessDays")
.getMany();
可能只是一个愚蠢的错误,但我似乎无法弄清楚。
【问题讨论】: