brianc / node-sql

SQL generation for node.js
MIT License
1.05k stars 191 forks source link

Is there a way to chain functions ? => Count(case) #350

Open Gerodork opened 7 years ago

Gerodork commented 7 years ago

I'm trying to get some specific data from my database. I found what request I needed in SQL, but it involves a count of a case. I tried just adding ".count()" at the end of my case but it says that it isn't a function. Here's the request in SQL

SELECT of.id, of.name, COUNT(CASE WHEN cast(command_lines.quantity AS INTEGER) - COALESCE(command_lines.quantity_delivered, 0) = 0 THEN 1 ELSE 0 END) AS lines_delivered, count(command_lines.id) AS line_ordered
FROM fabrication_orders of
LEFT JOIN command_lines ON command_lines.id_fabrication_orders = of.id
GROUP by of.id

And here's the supposed javascript

of.select(of.id, of.name,
commandLines.id.case([commandLines.quantity.cast('int').minus(sql.functions.COALESCE(commandLines.quantityDelivered,0)).equals(0)], [1], 0).count(), commandLines.id.count().as('nbOrdered')
            .from(of.leftJoin(commandLines).on(commandLines.idFabricationOrders.equals(of.id)))
            .group(of.id)

Anyone has an idea if it's already implemented? Or did I do something wrong? Thanks for any help !

gabe-ratcliff commented 7 years ago

Bump!

I have a similar case, where I want to use an in statement with an AND operator, instead of OR. This seems to be the only way to accomplish what I want.

let getCategoryCount = category_initiatives.categoryId
      .count()
      .distinct();
    getCategoryCount.alias = null;

    selectedInitiatives = selectedInitiatives
      .where( category_initiatives.categoryId.in( chosenCategories ) )
      .group( category_initiatives.initiativeId )
      .having( getCategoryCount.equals( chosenCategories.length ) );

The offending function is in the last line of the code. Above this snippet is the actual SELECT statement, etc.