将多行减少为单行

时间:2016-12-13 19:16:31

标签: sql sql-server

我正在尝试让我的数据库中所有具有某种技能的员工,例如管道。当我执行以下查询时,我得到了我想要的数据,但它不止一次地显示该员工。

SELECT
      TE.intEmployeeID
     ,TE.strLastName + ', ' + TE.strFirstName AS strEmployeeName
     ,CONVERT (VARCHAR, TE.dteHireDate, 101) AS dteHireDate
     ,TES.intSkillID
     ,TS.strSkills

 FROM
     TEmployees         AS TE
    ,TEmployeeSkills    AS TES
    ,TSkills            AS TS
    ,TJobEmployees      AS TJE
WHERE

        TE.intEmployeeID    =   TJE.intEmployeeID
    AND TS.intSkillID       =   TES.intSkillID
    AND TES.intEmployeeID   =   TE.intEmployeeID
    AND TES.intEmployeeID   =   TJE.intEmployeeID
    AND TES.intSkillID = 6

/*
What I am getting:

intEmployeeID   strEmployeeName   dteHireDate   intSkillID   strSkills
    2           Quagmire, Glen      06/10/2012      6         Plumbing
    4           Cage, Luke          01/10/2012      6         Plumbing
    4           Cage, Luke          01/10/2012      6         Plumbing
    2           Quagmire, Glen      06/10/2012      6         Plumbing
    2           Quagmire, Glen      06/10/2012      6         Plumbing
    4           Cage, Luke          01/10/2012      6         Plumbing

    What I need:

intEmployeeID   strEmployeeName   dteHireDate   intSkillID   strSkills
    2           Quagmire, Glen      06/10/2012      6         Plumbing
    4           Cage, Luke          01/10/2012      6         Plumbing
*/

1 个答案:

答案 0 :(得分:2)

尝试select distinct而非select

另外,我建议您更新加入语法。

select distinct 
      te.intEmployeeid
     ,te.strLastName + ', ' + te.strFirstName as strEmployeeName
     ,convert (varchar, te.dteHireDate, 101) as dteHireDate
     ,tes.intSkillid
     ,ts.strSkills
from temployees as te 
  inner join temployeeSkills as tes on tes.intEmployeeid = te.intEmployeeid 
    and tes.intSkillid = 6
  inner join tskills as ts          on ts.intSkillid     = tes.intSkillid
  inner join tjobEmployees as tje   on tje.intEmployeeid = te.intEmployeeid