在多个列中查找不同的值

Finding distinct values across multiple columns

我想创建一个函数来查找在其上工作的具有 sid(员工 ID)的 pno 的数量。 因此,例如,如果我想找到与 pno = 1

对应的 sid
select sid_worked_on(1)

 count 
-------
     2

我会得到 2 个,因为 sid 0 和 1 已经处理过了。

这是来自 3 个不同的 table 的合并 table。

 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

我唯一的想法是将 table“展平”到一列中,因为不需要多列并执行不同的 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 |
  ... 
  ...

我还想创建一个 table 并遍历每个值,所以

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。

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