【问题标题】:Typeorm SubqueryTypeorm 子查询
【发布时间】: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();

可能只是一个愚蠢的错误,但我似乎无法弄清楚。

【问题讨论】:

    标签: subquery typeorm


    【解决方案1】:

    要像第一个示例一样使用原始 SQL 进行查询,您需要使用 EntityManager.Query,如 TypeOrm 文档中的 EntityManager API 所述。

    What is EntityManager 下描述了如何获取EntityManager

    例子:

        const connection = await createConnection();
        const entitymanager = connection.manager;
        let result = await entitymanager.query("select top 1 TheDate from DateDimension order by TheDate desc");
        let theDate = result[0].TheDate;
    

    【讨论】:

      猜你喜欢
      • 2020-11-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-04
      • 2021-01-29
      • 2020-07-27
      • 2021-10-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多