1

需要在 Sequelize Node js 中编写如下 SQL Query

select a, b, c
from (
    select tbl.*, 
       count(*) over(partition by a) cnt,
       row_number() over (partition by a order by b) brn,
       row_number() over (partition by a order by c) crn
    from tbl
    where c in (4, 5)
) t
where cnt = 2 and brn = crn;

这就是我想出的。我不知道在哪里放置条件where cnt = 2 and brn = crn;

t.findAll({
    attributes: {
        include: [
            [sequelize.literal('count(*) over(partition by a)'),'cnt'],
            [sequelize.literal('row_number() over (partition by a order by b)'),'brn'],
            [sequelize.literal('row_number() over (partition by a order by c)'),'crn'],
        ]   
    },
    where: {
            c: {[Op.in]:[4,5]},
        }
    })
4

1 回答 1

1

Sequelize 似乎不支持从子查询中选择(https://github.com/sequelize/sequelize/issues/5354

您可以改用原始查询(https://sequelize.org/master/manual/raw-queries.html):

const { QueryTypes } = require('sequelize');
let result = await sequelize.query(`
    select a, b, c
    from (
        select tbl.*, 
           count(*) over(partition by a) cnt,
           row_number() over (partition by a order by b) brn,
           row_number() over (partition by a order by c) crn
        from tbl
        where c in (4, 5)
    ) t
    where cnt = 2 and brn = crn;
`, {type: QueryTypes.SELECT});
于 2021-05-08T15:36:28.557 回答