我想根据SQL中新创建的列进行筛选

我想根据SQL中新创建的列进行筛选,sql,postgresql,Sql,Postgresql,嘿,下面所有的行都来自PostgreSQL,它创建了一个值为Partial-Completed的新列,我想对它应用过滤器,但它给了我一个错误列状态不存在 TEXT(case when product_sales_order.purchased_item_count <> product_sales_order.issued_count then 'Partial' Else 'Completed' end) as status where sales_orders.deliver

嘿,下面所有的行都来自PostgreSQL,它创建了一个值为Partial-Completed的新列,我想对它应用过滤器,但它给了我一个错误列状态不存在

TEXT(case when product_sales_order.purchased_item_count <> product_sales_order.issued_count then 'Partial' Else 'Completed' end) as status

where  sales_orders.delivered_at::date >= '{{ From }}' AND sales_orders.delivered_at::date <= '{{ To }}' AND status = '{{status}}'


标准解是:

select x.*
from (select . . .,
             (case when product_sales_order.purchased_item_count <> product_sales_order.issued_count 
                   then 'Partial' Else 'Completed'
              end) as status
       from . . .
       where  sales_orders.delivered_at::date >= '{{ From }}' and
              sales_orders.delivered_at::date <= '{{ To }}'
      ) x
where status = '{{status}}';
注意:看起来您正在用输入值来填充查询字符串。您应该将这些作为参数传入。也就是说,查询可能如下所示:

select x.*
from (select . . .,
             (case when product_sales_order.purchased_item_count <> product_sales_order.issued_count 
                   then 'Partial' Else 'Completed'
              end) as status
       from . . .
       where  sales_orders.delivered_at::date >= ? and
              sales_orders.delivered_at::date <= ?
      ) x
where status = ?;

在哪里?是表示参数占位符的典型方式。

使用子查询、CTE或横向联接。此外,您的查询语法无效,因此问题有点难以理解。您确切的意思是什么?我想将下面的行定义为表,以便在产品销售订单、采购商品数量、产品销售订单、已发布数量、然后“部分”或“已完成”结束为状态时对其进行文本筛选