Postgresql count based on condition

I am executing this query

SELECT COUNT(designer_orders.id) as pr, 
       SUM(IF designer_orders.package_status == 'packed' THEN 0 ELSE 1 END) as pu 
FROM "designer_orders"

Expected output

PR PU
10 5

Getting Output

PR PU
10 0

This block of query not working as expected

SUM(IF designer_orders.package_status == 'packed' THEN 0 ELSE 1 END)

Answers


Try this:

SELECT COUNT(designer_orders.id) as pr, SUM(CASE WHEN designer_orders.package_status = 'packed' THEN 0 ELSE 1 END) as pu FROM "designer_orders"

There is no IF in SQL, you need to use CASE.

Additionally the equality operator in SQL is = not ==

SELECT COUNT(id) as pr, 
       SUM(CASE WHEN package_status = 'packed' THEN 0 ELSE 1 END) as pu 
FROM designer_orders;

For an introduction into SQL, please see this chapter of the manual: http://www.postgresql.org/docs/current/static/tutorial-sql.html

For a description of available operators, please see here: http://www.postgresql.org/docs/current/static/functions-conditional.html


Need Your Help

Can OpenLaszlo Use JavaScript Libraries like JQuery and PrototypeJS?

javascript jquery prototypejs openlaszlo

I have been looking at OpenLaszlo and observed that scripting in the client is implemented in JavaScript. Does this mean it is possible to use libraries like JQuery and PrototypeJS ?

redirect output to terminal

bash echo stdout stderr io-redirection

I am trying to understand redirecting the output.