带有递归查询的Postgresql

时间:2013-11-11 07:22:36

标签: postgresql

尝试递归后我有疑问

我正在尝试使用两个表

第一个表格是complain_table

complain                   product_id
----------------------------------------
Not working          -          1
not working                     1
not working                     1
Loading problem                 2
Loading problem                 2

第二张表product_table

Name     id                      
--------------
usb      1
cd       2

现在我想要的输出是

product                complain
-----------------------------------
usb                   Not working
                      Not working
                      Not working
cd                    Loading problem
                      Loading problem

1 个答案:

答案 0 :(得分:1)

如果您希望输出如图所示(抑制重复的产品名称),则应执行以下操作:

select case 
         when row_number() over (partition by p.name order by ct.complain) = 1 then p.name
         else null
       end as product,
       ct.complain
from products p
  join complain_table ct on p.product_id = ct.product_id
order by p.product_id;

顺便说一句:您的complain_table看起来应该complain_reason_id引用complain_reason_text表,以避免一遍又一遍地重复相同的投诉文本