[英]Joining two tables on keys where key name is column names
I'm trying to join two tables where the first tables contains ID's and measure.我正在尝试连接两个表,其中第一个表包含 ID 和度量。
Skey | ID | Measure
1 | A1 | 12
2 | A1 | 34
3 | A2 | Green
4 | A4 | 0.00005
The second tables contains the table name ID and ID data type.第二个表包含表名 ID 和 ID 数据类型。
ID | DataType
A1 | int
A2 | character
A4 | decimal
I want to do a join using these tables which will result in the following table我想使用这些表进行连接,结果如下表
Skey | ID | int | character | decimal
1 | A1 | 12 | NA | NA
2 | A1 | 34 | NA | NA
3 | A2 | NA | Green | NA
4 | A4 | NA | NA | 0.00005
Can this be done?这能做到吗? If yes, need to understand the logic and the way to accomplish it.如果是,则需要了解其逻辑和实现方式。
What fun!多么有趣! You can join
and use case
:您可以join
并使用case
:
select t1.skey, t1.id,
(case when t2.type = 'int' then cast(t2.measure as int) end) as int_col,
(case when t2.type = 'character' then cast(t2.measure as varchar(255)) end) as int_col,
(case when t2.type = 'int' then cast(t2.measure as decimal) end) as decimal_col
from table1 t1 join
table2 t2
on t1.id = t2.id;
A couple of caveats:几个警告:
'0.0005'
to 0.0005
, some to 0
.一些数据库会将字符串'0.0005'
转换为0.0005
,一些转换为0
。 You might need to include precision and scale for the actual conversion.您可能需要为实际转换包括精度和小数位数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.