当右表中有多个值时,左连接没有来自左表的重复值

时间:2016-11-10 14:53:20

标签: sql sql-server sql-server-2008

以下查询会返回ID列表和时间列表。它从Left表中返回multimple,因为它在右表中显示为多个。

目前它带回了这个:

enter image description here

我希望它从右表中为左表中的每个ID带回最小值。

任何帮助表示赞赏!

set language british 
SELECT dbo.Employee.EmployeeID, SUBSTRING(CONVERT(varchar, ClockTemp.ClockTime, 108), 1, 5) as ClockTime
FROM  dbo.Employee LEFT JOIN 
(
    Select [ClockID]
      ,[EmployeeID]
      ,[ClockTypeID]
      ,[ClockDate]
      ,[ClockTime] 
    FROM dbo.Clock 
    WHERE dbo.Clock.ClockDate = DATEADD(DD, 0, CAST('07-11-2016' AS DATE)) AND Clock.ClockTypeID=1
) As ClockTemp
ON dbo.Employee.EmployeeID = ClockTemp.EmployeeID
ORDER BY dbo.Employee.EmployeeID,clocktemp.ClockTime

3 个答案:

答案 0 :(得分:0)

也许这个查询对你有用。您不需要按Clocktime订购,因为最小值将从MIN聚合中获得。

如果您使用SQL 2008,我还会将Clocktime字段更改为TIME,以便您可以避免子字符串转换。

set language british 
SELECT dbo.Employee.EmployeeID, SUBSTRING(CONVERT(varchar, MIN(ClockTemp.ClockTime), 108), 1, 5) as ClockTime
FROM  dbo.Employee LEFT JOIN 
(
    Select [ClockID]
      ,[EmployeeID]
      ,[ClockTypeID]
      ,[ClockDate]
      ,[ClockTime] 
    FROM dbo.Clock 
    WHERE dbo.Clock.ClockDate = DATEADD(DD, 0, CAST('07-11-2016' AS DATE)) AND Clock.ClockTypeID=1
) As ClockTemp
ON dbo.Employee.EmployeeID = ClockTemp.EmployeeID
GROUP BY dbo.Employee.EmployeeID
ORDER BY dbo.Employee.EmployeeID

答案 1 :(得分:0)

试试:

WITH minClockTimeCTE AS (
  SELECT EmployeeID, min(ClockTime) as ClockTime
  FROM ClockTemp
  GROUP BY EmployeeID
)
SELECT Employee.EmployeeID, minClockTimeCTE.ClockTime
FROM Employee
LEFT OUTER JOIN minClockTimeCTE 
  ON Employee.EmployeeID = minClockTimeCTE.EmployeeID

答案 2 :(得分:0)

您可以将左连接更改为外部应用顶部1:

SELECT dbo.Employee.EmployeeID, 
  SUBSTRING(CONVERT(varchar, ClockTemp.ClockTime, 108), 1, 5) as ClockTime
FROM  dbo.Employee 
OUTER APPLY 
(
    SELECT TOP 1 [ClockID]
        ,[EmployeeID]
        ,[ClockTypeID]
        ,[ClockDate]
        ,[ClockTime] 
    FROM dbo.Clock 
    WHERE dbo.Clock.ClockDate = DATEADD(DD, 0, CAST('07-11-2016' AS DATE)) 
        AND Clock.ClockTypeID=1
        AND dbo.Employee.EmployeeID = ClockTemp.EmployeeID
    ORDER BY ClockTime
) As ClockTemp
ORDER BY dbo.Employee.EmployeeID,clocktemp.ClockTime