2013-11-21 143 views
0

我想要一個SQL查詢,確定與特定值的行中Table1存在,或Table2,或兩者的SQL Server 2008 - T-SQL查詢

這裏是我寫的,但它只給我值存在於第一個表中,但如果它存在於第二個表中,但不在第一個表中。我希望結果正如我上面的陳述一樣。

SELECT CASE 
     WHEN EXISTS (SELECT Offerid 
         FROM dbo.OfferLocations 
         EXCEPT 
         SELECT Offerid 
         FROM dbo.OfferLocUpdate) THEN 1 
     ELSE 0 
     END 
+0

什麼是您的比較標準? –

+0

我希望offerid在結果中顯示,如果它存在於第一個tabl或第二個表中或兩者都存在 – user2041076

+0

我根據locationid – user2041076

回答

0

你需要一個FULL OUTER JOIN,如下圖所示:

; 
WITH OfferLocations AS -- Sample data, ignore it 
     ( SELECT OfferId 
      FROM (VALUES (1), (2), (3)) OfferLocations(OfferId) 
     ), 
     OfferLocUpdate AS -- Sample data, ignore it 
     ( SELECT OfferId 
      FROM (VALUES (2), (3), (4)) OfferLocUpdate(OfferId) 
     ) 
SELECT  ISNULL(OfferLocations.OfferId, OfferLocUpdate.OfferId) OfferId, 
      CASE WHEN OfferLocations.OfferId IS NULL THEN 0 ELSE 1 END [ExistsAtOfferLocations], 
      CASE WHEN OfferLocUpdate.OfferId IS NULL THEN 0 ELSE 1 END [ExistsAtOfferLocUpdate] 
FROM  OfferLocations 
FULL OUTER JOIN OfferLocUpdate 
      ON OfferLocations.OfferId = OfferLocUpdate.OfferId 
ORDER BY ISNULL(OfferLocations.OfferId, OfferLocUpdate.OfferId) 
0

嘗試UNION而不是EXCEPT?這將得到兩個表dbo.OfferLocationsdbo.OfferLocUpdate中不同的Offerid。

SELECT CASE 
    WHEN EXISTS (SELECT Offerid 
        FROM dbo.OfferLocations 
        UNION 
        SELECT Offerid 
        FROM dbo.OfferLocUpdate) THEN 1 
    ELSE 0 
    END