PostgreSQL:通过基于多行中的列值过滤行来创建新视图

时间:2017-03-21 09:51:36

标签: postgresql magento

我正在使用像这样的magento表:

hdnStartTime.Value

我想创建一个新视图,首先查找具有相同order_id和product_id的行。然后在这两行中,我想只取一行product_type =" custom"。我想也只采取某些列。

所以我从上面做这个操作后的最终表应该是这样的:

+---------------------------------------------------------------------------------+
| date product_name product_id product_type time order_id qty_ordered last_order  |
+---------------------------------------------------------------------------------+
| 2017/2/15 X 18W1 custom 1900 12 1 2016/12/10                                    |
| 2017/2/15 X 18W1 simple 1900 12 1 2016/12/3                                     |
| 2017/2/15 XX 18W2 simple 1900 12 3 2016/12/4                                    |
| 2017/2/20 Y 22Y34 simple 1532 19 1 2017/1/9                                     |
| 2017/2/20 Z 22Y35 simple 1532 19 2 2017/1/15                                    |
| 2017/2/20 Z 22Y35 custom 1532 19 2 2016/9/12                                    |
+---------------------------------------------------------------------------------+

到目前为止,我已尝试使用以下查询无效:

+-----------+--------------+------------+--------------+----------+-------------+
| date      | product_name | product_id | product_type | order_id | qty_ordered |
+-----------+--------------+------------+--------------+----------+-------------+
| 2017/2/15 |            X |       18W1 |       custom | 12       | 1           |
+-----------+--------------+------------+--------------+----------+-------------+
| 2017/2/15 | XX           | 18W2       | simple       | 12       | 3           |
+-----------+--------------+------------+--------------+----------+-------------+
| 2017/2/20 | Y            | 22Y34      | simple       | 19       | 1           |
+-----------+--------------+------------+--------------+----------+-------------+
| 2017/2/20 | Z            | 22Y35      | custom       | 19       | 2           |
+-----------+--------------+------------+--------------+----------+-------------+

非常感谢任何帮助,谢谢!

1 个答案:

答案 0 :(得分:0)

您可以通过选择所有自定义条目,然后选择那些没有相应自定义条目的简单条目来完成此操作。类似的东西:

create view v_tab
as
select * from tab where product_type = 'custom'
union all
select * from tab t1 where product_type = 'simple' and
  not exists 
    (select * from tab t2 
     where t2.order_id = t1.order_id 
     and t2.product_id = t1.product_id 
     and t2.product_type = 'custom')