Table 1
-------
LANG_VALUE
LANG_DESC
Table 2
-------
EmpId
LANG1
LANG2
LANG3
LANG4
LANG5
LANG6
如下所示:
Table 1
-------
LANGVALUE LANGDESC
-------------------
SPAN SPANISH
GERM GERMAN
Table 2
-------
EmpId LANG1 LANG2 LANG3 LANG4 LANG5 LANG6
-----------------------------------------
1 SPAN NULL NULL NULL NULL NULL
2 GERM SPAN NULL NULL NULL NULL
3 GERM NULL NULL NULL NULL NULL
预期结果:
EmpId LANG1 LANG2 LANG3 LANG4 LANG5 LANG6
-----------------------------------------
1 SPANISH NULL ...
2 GERMAN SPANISH NULL...
3 GERMAN NULL...
如何在sql查询中执行此操作?
答案 0 :(得分:2)
SELECT EmpId,
K1.LANGDESC AS LANG1,
K2.LANGDESC AS LANG2,
K3.LANGDESC AS LANG3,
K4.LANGDESC AS LANG4,
K5.LANGDESC AS LANG5,
K6.LANGDESC AS LANG6
FROM Table2 T
LEFT JOIN Table1 K1 ON K1.LANGVALUE = T.LANG1
LEFT JOIN Table2 K2 ON K2.LANGVALUE = T.LANG2
LEFT JOIN Table3 K3 ON K3.LANGVALUE = T.LANG3
LEFT JOIN Table4 K4 ON K4.LANGVALUE = T.LANG4
LEFT JOIN Table5 K5 ON K5.LANGVALUE = T.LANG5
LEFT JOIN Table6 K6 ON K6.LANGVALUE = T.LANG6
WHERE...
注意:这个问题主动提出,但以一对多的方式考虑将Employee to Language存储在单独的表中的架构可能是个好主意。这将允许拥有超过6种语言的员工(希望您拥有多种语言......)以及不为那些不那么多语言的员工提供如此多的空值,更重要的是,它将允许查询说所有员工都有特殊语言,无需担心是否可以在LANG2或LANG3等中找到...
注意,Employee-Langage表还可以有一个表示“订单”(或流畅程度)的属性,这样您也可以搜索第一个列出的语言为x的员工。
答案 1 :(得分:0)
我认为您必须根据表格2的格式对子查询执行此操作。我有明显感觉您没有针对表格2进行正确规范化,这就是为什么您首先遇到此问题的原因
select EmpId,(Select LANGDESC from [Table 1] t1 where t2.Lang1=LANGVALUE) as LANG1,(and so on) where from [Table 2] t2