首页 > 解决方案 > 如何根据列标题名称执行查找?

问题描述

希望有人可以协助构建以下查询。

代码类型

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&IDTypeValues表中针对特定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'

标签: sql-servertsqlpivot

解决方案


您可以使用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

推荐阅读