Postgresql 跨多个列查找不同的值

Postgresql 跨多个列查找不同的值,postgresql,plpgsql,Postgresql,Plpgsql,我想创建一个函数,用于查找使用sid(员工id)的pno的数量。 例如,如果我想找到对应于pno=1的sid select sid_worked_on(1) count ------- 2 我会有2个,因为sid 0和1已经在处理它 这是来自3个不同表的联接表 pno | a_sid | b_sid | c_sid -----+--------+--------+-------- 1 | 0 | 0 | 0 4 | 4

我想创建一个函数,用于查找使用sid(员工id)的pno的数量。 例如,如果我想找到对应于pno=1的sid

select sid_worked_on(1)

 count 
-------
     2
我会有2个,因为sid 0和1已经在处理它

这是来自3个不同表的联接表

 pno |  a_sid |  b_sid |  c_sid
-----+--------+--------+--------
   1 |      0 |      0 |      0
   4 |      4 |      4 |      6
   5 |      4 |      4 |      5
   2 |      0 |      0 |      0
   1 |      0 |      1 |      0
   7 |      5 |      4 |      4
   7 |      5 |      5 |      4
   5 |      4 |      4 |      4
   4 |      4 |      5 |      6
   7 |      5 |      4 |      1
   7 |      5 |      5 |      1
   6 |      5 |      4 |      5

我唯一的思考方法是将表“展平”为一列,因为不需要多列并执行不同的sid,但我还没有学会如何做到这一点

pno  |  sid 
-----+--------
   1 |      0 | 
   4 |      4 |
   5 |      4 |
   2 |      0 |    
   1 |      0 |  
   7 |      5 |   
   7 |      5 |
   5 |      4 | 
   4 |      4 |     
   7 |      5 |
   7 |      5 | 
   6 |      5 |   
--where the new table starts
   1 |      0 |
   4 |      4 | 
   5 |      4 | 
   2 |      0 |
   1 |      1 |
   7 |      4 |
  ... 
  ...
我还想创建一个表并遍历每个值,所以

create table
for each row where pno = 1
       check if a_sid in table
           if not then add a_sid to table
       check if b_sid in table 
           if not then add b_sid to table
       check if c_sid in table
           if not then add c_sid to table
有更好的方法吗?

使用UNION

SELECT pno, a_sid from table
UNION
SELECT pno, b_sid from table
UNION
SELECT pno, c_sid from table
根据您是否希望右侧具有相同列的相同pno的重复条目,可以使用UNION ALL而不是UNION


您可以使用此查询创建视图。

我无法理解您对所需内容的描述。