Postgresql根据条件计算

时间:2014-03-12 10:51:02

标签: sql postgresql

我正在执行此查询

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

预期输出

PR PU
10 5

获得输出

PR PU
10 0

此查询块未按预期工作

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

2 个答案:

答案 0 :(得分:3)

SQL中没有IF,您需要使用CASE

此外,SQL中的等于运算符为=而不是==

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

有关SQL的介绍,请参阅手册的这一章:http://www.postgresql.org/docs/current/static/tutorial-sql.html

有关可用运营商的说明,请参阅此处:http://www.postgresql.org/docs/current/static/functions-conditional.html

答案 1 :(得分:1)

试试这个:

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"