如何获取表中不存在但在sql server中另外两个表中出现的记录

时间:2015-08-21 12:48:30

标签: sql

表1

MachineName
AQUA       
MAMMO      
NAZO789    

表2

ShiftName
First
Second
Third

表3

Date           Shift         MachineName
21/08/2015     First            AQUA 
21/08/2015     First          NAZO789
21/08/2015     Second          MAMMO
21/08/2015     Second           AQUA 
21/08/2015     Third          NAZO789

现在我希望输出日期为21/08/2015,其条目不在表3中 对于MachineName和ShiftName

喜欢:

Date           Shift         MachineName
21/08/2015     Third           AQUA 
21/08/2015     Second         NAZO789
21/08/2015     First          MAMMO
21/08/2015     Third          MAMMO

2 个答案:

答案 0 :(得分:1)

MS SQL Server。更新为日期范围提供所有缺失的组合(包括在给定日期没有任何内容)。

DECLARE @StartDate DATE='21/08/2015'
DECLARE @EndDate DATE='26/08/2015'

DECLARE @Dates TABLE (
    [DATE] DATE
)

DECLARE @counter int=0
WHILE DATEADD(DAY,@counter,@StartDate)<=@EndDate
    BEGIN
        INSERT INTO @Dates SELECT DATEADD(DAY,@counter,@StartDate)

        SET @counter=@counter+1
    END

SELECT
   @Date [Date],sn.ShiftName,mn.MachineName
FROM MachineName mn
CROSS JOIN ShiftName sn
CROSS JOIN @Dates dt
LEFT JOIN (
   SELECT
      *
   FROM TABLE3
   WHERE Date>=@StartDate
   AND Date<=@EndDate
) dat ON dat.MachineName=mn.MachineName
    AND dat.[Shift]=sn.ShiftName
    AND dat.[Date]=dt.[DATE]
WHERE dat.MachineName IS NULL

答案 1 :(得分:0)

这将为您提供表3中不存在的所有组合:

Select b.ShiftName,a.MachineNameFrom

    (Select MachineName,'join' as joiner
    From Table1) a

inner join

    (Select ShiftName,'join' as joiner
    From Table2) b

on a.joiner = b.joiner

EXCEPT

Select Shift,MachineName From
Table3