简体   繁体   中英

Can Knex do "HAVING COUNT(col) > x" without resorting to raw?

I want to build the following query using knex (in typescript), and I'm puzzled by the HAVING COUNT. The knex website seems to indicate that it can only be done with HavingRaw , but I'm curious if there is solution without using raw SQL.

The query in SQL:

SELECT UserId, COUNT(UserId)
FROM [MyTable] 
WHERE UserId IS NOT NULL 
AND OrderDate BETWEEN '2022-01-10T00:00:00.000Z' AND '2022-01-14T23:59:59.999Z'
GROUP BY UserId
HAVING COUNT(UserId) >= 5

My current implementation:

    const mainQuery = knexDb('MyTable')
        .select('UserId')
        .count('UserId')
        .whereNotNull('UserId')
        .whereBetween('TargetDate', [date1, date2])
        .groupBy('UserId')
        .havingRaw('COUNT(UserId) >= ?', [5]);

I'm curious if there is a built-in, typed, alternative for the .havingRaw('COUNT(UserId) >=?', [5]); part

In your specific example you could alias the count in your select and then just reference that in the having clause. ie

const mainQuery = knexDb('MyTable')
        .select('UserId')
        .count('UserId as UserCount')
        .whereNotNull('UserId')
        .whereBetween('TargetDate', [date1, date2])
        .groupBy('UserId')
        .having('UserCount', '>=', 5);

If you do not already have the column you are counting in your select then I don't think it's possible without raw currently.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM