sql中的相同表,查找一个不在另一个中的行

时间:2013-11-19 14:20:42

标签: sql sql-server-2008-r2

我有两张相同的桌子。我想找到一个但不在另一个的记录。

enter image description here

我一直在使用此查询,但我仍然会收到重复记录。

select a.storeid
    ,a.cashierid
    ,a.registerid
    ,a.timein
    ,a.timeout
    ,a.hours
    ,a.cashierprofile
from Timecard a
where not exists(select null from timecardssl b 
                        where b.StoreID = a.StoreID 
                             and b.CashierID = a.CashierID 
                             and b.RegisterID = a.RegisterID 
                             and b.TimeIn = a.TimeIn  
                             and b.TimeOut = a.TimeOut  
                             and b.hours = a.hours 
                             and b.CashierProfile = a.CashierProfile )
group by a.storeid
    ,a.cashierid
    ,a.registerid
    ,a.timein
    ,a.timeout
    ,a.hours
    ,a.cashierprofile 
having count(*) = 1
order by TimeIn desc

4 个答案:

答案 0 :(得分:2)

这听起来像LEFT OUTER JOIN被发明了:) 如果您在TimeCard中有相同的记录而您不想看到它们,请使用DISTINCT

    SELECT DISTINCT a.storeid,a.cashierid,a.registerid,a.timein,a.timeout,a.cashierprofile
      FROM Timecard a
LEFT OUTER JOIN timecardssl b 
        ON b.StoreID = a.StoreID 
       and b.CashierID = a.CashierID 
       and b.RegisterID = a.RegisterID     
       and b.TimeIn = a.TimeIn 
       and b.TimeOut = a.TimeOut 
       and b.CashierProfile = a.CashierProfile
     WHERE b.StoreID IS NULL;

请注意,我遗漏了“小时”列 比较两个小时的列给出了一些奇怪的结果,这是值得深入研究的。 但由于小时数是timeIn和timeOut之间的差异,因此将其删除不会造成伤害(如果timeIn和timeOut相等,那么你已经有了相同的记录!)

答案 1 :(得分:0)

以下内容如何:

SELECT DISTINCT a.storeid, a.cashierid, a.registerid, 
  a.timein, a.timeout, a.hours, a.cashierprofile
FROM Timecard a
WHERE NOT EXISTS
(
  SELECT Null
  FROM timecardssl b 
  WHERE b.StoreID = a.StoreID 
  AND b.CashierID = a.CashierID 
  AND b.RegisterID = a.RegisterID
  AND b.TimeIn = a.TimeIn 
  AND b.TimeOut = a.TimeOut
  AND b.hours = a.hours 
  AND b.CashierProfile = a.CashierProfile 
)
ORDER BY TimeIn desc

答案 2 :(得分:0)

timecard表中不在timecardsssl表中的记录。

SELECT storeid
     , cashierid
     , registerid
     , timein
     , timeout
     , hours
     , cashierprofile
FROM   timecard

EXCEPT

SELECT storeid
     , cashierid
     , registerid
     , timein
     , timeout
     , hours
     , cashierprofile
FROM   timecardssl

timecardssl表中不在timecards表中的记录。

SELECT storeid
     , cashierid
     , registerid
     , timein
     , timeout
     , hours
     , cashierprofile
FROM   timecardssl

EXCEPT

SELECT storeid
     , cashierid
     , registerid
     , timein
     , timeout
     , hours
     , cashierprofile
FROM   timecard

答案 3 :(得分:0)

尝试这样的事情:

SELECT ...
FROM Timecard
UNION DISTINCT ...
FROM timecardssl 
GROUP BY ... 
HAVING COUNT(*) = 1