繁体   English   中英

SYBASE:加入两个表,其中一个表列的值是另一表的列名

[英]SYBASE :Join Two table where Value of one table column is column name of other table

  Table1 

PRICE   ID_1    ID_2    ID_3
 500    1       2       3
 750    2       3       4  


Table2

ID  VALUE  
ID_1    1  
ID_2    2  
ID_3    3  

我有两个表,想要加入这些表,例如

Select * from table1 T1 Join Table2 T2 on
T1.(T2.ID) = T2.Value

简而言之,我想在加入时将一个表列的值转换为另一表列的名称。

编辑结果应如下所示:

PRICE   ID_1    ID_2    ID_3  
 500    1       2       3

您需要先将第二个表中的行转换为列,然后将两个表连接起来:

Select * 
from table1 T1 
join
(

    SELECT
      MAX(case when id = 'ID_1' THEN Value ELSE 0 END) AS ID_1,
      MAX(case when id = 'ID_1' THEN Value ELSE 0 END) AS ID_2,
      MAX(case when id = 'ID_1' THEN Value ELSE 0 END) AS ID_3
    from table

) as T2  on T1.ID_1 = T2.ID_1
        and T1.ID_2 = T2.ID_2
        and T1.ID_3 = T2.ID_3

或通过另一种方式将表中的列转换为行:

SELECT *
FROM
(
    SELECT 'ID_1' AS ID, ID_1 AS Value from table1
    UNION ALL
    SELECT 'ID_2' AS ID, ID_2 AS Value from table1
    UNION ALL
    SELECT 'ID_3' AS ID, ID_3 AS Value from table1
) AS t1
INNER JOIN Table2 as T2  on T1.ID_1 = T2.ID_1
                        and T1.ID_2 = T2.ID_2
                        and T1.ID_3 = T2.ID_3;

一种方法是:

Select *
from table1 T1 Join
     Table2 T2
     on t1.id_1 = T2.Value and t2.id = 'ID_1' or
        t1.id_2 = T2.Value and t2.id = 'ID_2' or
        t1.id_3 = T2.Value and t2.id = 'ID_3';

这效率不高,但是应该可以实现所需的逻辑。

编辑:

根据您的编辑,您似乎想要:

select t1.*
from table1 t1
where exists (select 1 from table2 where t2.value = t1.id_1 and t2.id = 'ID_1') and
      exists (select 1 from table2 where t2.value = t1.id_2 and t2.id = 'ID_2') and
      exists (select 1 from table2 where t2.value = t1.id_3 and t2.id = 'ID_3') ;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM