SQL查询返回重复行

时间:2014-12-01 16:45:50

标签: sql sql-server tsql

SELECT  E.SSN AS SocialSecurityNumber ,
        E.Name + ' ' + E.LastName AS FullName ,
        J.Job ,
        R.Date ,
        R.STime AS StartTime,
        R.ETime AS EndTime,
        CASE WHEN R.Date BETWEEN O.SDate AND O.EDate THEN O.OffID
             ELSE 0
        END AS OffReason
FROM    Resume AS R
        INNER JOIN Employees AS E ON E.ID = R.EmpID
        INNER JOIN Jobs AS J ON J.ID = E.JobID
        LEFT JOIN Offs AS O ON E.ID = O.EmpID
                               AND R.Date BETWEEN O.SDate AND O.EDate
WHERE   E.JobLeft = 0
        AND R.Date BETWEEN '2014-11-26 00:00:00'
                   AND     '2014-11-26 23:59:59'
ORDER BY FullName

我为员工简历报告程序写了这个SQL查询。我想检查员工何时开始工作,如果他们有理由不去工作,请返回reasonId或者如果他们没有检索0。在此查询中,当有两个或更多offreasons时,结果返回重复的行对于同一名员工。喜欢度假&法定节假日。我搜索了这个,但找不到相同的情况。删除的行并不重要;一个offreason足够我。所以我尝试了DISTINCT关键字,但它没有解决问题。那么我该怎么做才能解决这个问题呢?

1 个答案:

答案 0 :(得分:2)

最简单的方法是仅使用MAX选择其中一个原因:

SELECT E.SSN                     AS SocialSecurityNumber, 
       E.Name + ' ' + E.LastName AS FullName, 
       J.Job, 
       R.DATE, 
       R.STime                   AS Start, 
       R.ETime                   AS END, 
       MAX(CASE 
             WHEN R.DATE BETWEEN O.SDate AND O.EDate THEN O.OffID 
             ELSE 0 
           END)                  AS OffReason 
FROM   Resume AS R 
       INNER JOIN Employees AS E 
               ON E.ID = R.EmpID 
       INNER JOIN Jobs AS J 
               ON J.ID = E.JobID 
       LEFT JOIN Offs AS O 
              ON E.ID = O.EmpID 
                 AND R.DATE BETWEEN O.SDate AND O.EDate 
WHERE  E.Left = 0 
       AND R.DATE BETWEEN '2014-11-26 00:00:00' AND '2014-11-26 23:59:59' 
GROUP  BY E.SSN, 
          E.Name + ' ' + E.LastName, 
          J.Job, 
          R.DATE, 
          R.STime, 
          R.ETime 
ORDER  BY FullName