0

答案:这是根据@Michael 的答案构建的最终查询:

SELECT 
    Emp_ID,
    MAX(CASE WHEN Skill_ID = 'WLN' THEN (Rating > 0) END) AS `WLN`,
    MAX(CASE WHEN Skill_ID = 'LOC' THEN (Rating > 0) END) AS `LOC`,
    MAX(CASE WHEN Skill_ID = 'BRV' THEN (Rating > 0) END) AS `BRV`,
    AVG(CASE WHEN Skill_ID IN ('KWH','SIC','DOL') THEN (Rating) END) > 0 AS `KSD`
FROM Emp_Skill
WHERE Emp_ID IN (120,348,361,370)
GROUP BY Emp_ID

问题

我有下Emp_Skill表:

Skill_ID*  Emp_ID*  Rating
--------------------------
     WLN      120        6
     WLN      348        5
     WLN      361        7
     WLN      370        8
     LOC      120        7
     LOC      370        7
     LOC      348        7
     BRV      120        3
     LOC      361        6
     BRV      348        1
     KWH      348        5
     KWH      120        5
     KWH      361        5
     KWH      370        5
     SIC      361        8
     SIC      348        4
     SIC      120        2
     DOL      348        5
     DOL      361        8

我需要知道是否有任意数量的员工对每项技能都有积极的技能评分

因此,假设我想查看员工120、348、361370信息。

技能查询1WLN是:

SELECT `Emp_ID`, `Rating` > 0 AS `WLN` FROM `Emp_Skill` WHERE `Skill_ID` = 'WLN' AND `Emp_ID` IN (120,348,361,370)

返回:

Emp_ID   WLN
------------
   120     1
   348     1
   361     1
   370     1

技能查询2LOC是:

SELECT `Emp_ID`, `Rating` > 0 AS `LOC` FROM `Emp_Skill` WHERE `Skill_ID` = 'LOC' AND `Emp_ID` IN (120,348,361,370)

返回:

Emp_ID   LOC
------------
   120     1
   348     1
   361     1
   370     1

技能查询 3BRV是:

SELECT `Emp_ID`, `Rating` > 0 AS `BRV` FROM `Emp_Skill` WHERE `Skill_ID` = 'BRV' AND `Emp_ID` IN (120,348,361,370)

返回:

Emp_ID   BRV
------------
   120     1
   348     1

并且技能查询4KSD是:

SELECT `Emp_ID`, AVG(`Rating`) > 0 AS `KSD` FROM `Emp_Skill` WHERE `Skill_ID` IN ('KWH','SIC','DOL') AND `Emp_ID` IN (120,348,361,370) GROUP BY `Emp_ID`

返回:

Emp_ID   KSD
------------
   120     1
   348     1
   361     1
   370     1

问题是:如何有效地将这些查询组合到一个结果表中,并一次性将它们全部包含在内,即:

Emp_ID   WLN   LOC   BRV   KSD
------------------------------
   120     1     1     1     1
   348     1     1     1     1
   361     1     1  NULL?    1
   370     1     1  NULL?    1

可能来自综合SELECT声明?(该NULL值可以是FALSE返回结果集中计算结果的任何值)

或者:在性能方面,如果我只是一个一个地查询每个技能等级(使用上面的 4 个查询)会更好吗?

对不起,如果这对于那里的一些窥视者来说是基本的,但我已经拉了很多头发,我还没有杀死它。哈哈。提前致谢。

4

1 回答 1

1

这是通过一个数据透视查询完成的,它相当于一堆CASE语句。我认为这应该让你接近你所需要的:

SELECT 
  Emp_ID,
  MAX(CASE WHEN Skill_ID = 'WLN' THEN  (Rating > 0) END) AS `WLN`,
  MAX(CASE WHEN Skill_ID = 'LOC' THEN  (Rating > 0) END) AS `LOC`,
  MAX(CASE WHEN Skill_ID = 'BRV' THEN  (Rating > 0) END) AS `BRV`,
  AVG(CASE WHEN Skill_ID IN ('KWH','SIC','DOL') THEN  (Rating > 0) END) AS `KSD`
FROM Emp_Skill
GROUP BY Emp_ID
于 2012-06-07T02:44:57.337 回答