sql-server - 如何根据列标题名称执行查找?
问题描述
希望有人可以协助构建以下查询。
代码类型
Code | ID | Type
---------------------
ABC | 1234 | 'Type1'
ABC | 1234 | 'Type2'
CDE | 2345 | 'Type1'
CDE | 2345 | 'Type3'
EFG | 3456 | 'Type2'
类型值
Code | ID | Type1 | Type2 | Type3
----------------------------------------
ABC | 1234 | ';kjap' | ')&jaa' | '123ja'
CDE | 2345 | NULL | '$@#$a' | 'asdfa'
EFG | 3456 | '&*(01' | 'jmblk' | NULL
我希望能够构造尾随列“TypeValue”,它本质上是基于Code
&ID
在TypeValues
表中针对特定Type
.
Code | ID | Type | TypeValue
----------------------------------
ABC | 1234 | 'Type1' | ';kjap'
ABC | 1234 | 'Type2' | ')&jaa'
CDE | 2345 | 'Type1' | NULL
CDE | 2345 | 'Type3' | 'asdfa'
EFG | 3456 | 'Type2' | 'jmblk'
解决方案
您可以使用CASE
来选择要使用的列。例如:
select
t.*,
case when t.type = 'Type1' then v.type1
when t.type = 'Type2' then v.type2
when t.type = 'Type3' then v.type3
end as typevalue
from codetypes t
join typevalues v on v.code = t.code and v.id = t.id
根据 HABO 的评论编辑:
查询可以进一步简化为:
select
t.*,
case t.type when 'Type1' then v.type1
when 'Type2' then v.type2
when 'Type3' then v.type3
end as typevalue
from codetypes t
join typevalues v on v.code = t.code and v.id = t.id
推荐阅读
- python - Generator expression vs list comprehension for adding values to a set
- tree - 我想存储树后序遍历而不是打印它?我正在使用递归方法。它如何在数组中存储正确的顺序?
- python-3.x - 碰撞检测:球落地平台
- database - 如何不使用 laravel eloquent 根据另一个表中的记录获取一些数据?
- javascript - “依赖下拉列表”不起作用[谷歌应用引擎上的烧瓶]
- google-sheets - 查询中的变量命名范围单元格引用
- android - 如何在 Flutter 上禁用或处理最小化应用程序功能
- python - AttributeError:模块“app.management.commands.api”没有属性“命令”
- android - java.lang.NullPointerException:当我从数据库中删除图像时出现uriString
- docker - 如何在 Dockerfile 中获取当前日期?