使用XOR声明加入条款

时间:2015-02-09 15:00:39

标签: sql join sql-server-2000 xor

我正在加入,我似乎无法正常工作。

SELECT t1.COMPANY, t1.MILES,
   CASE WHEN t2.MILES IS NULL THEN t3.MILES
        ELSE t2.MILES
   END AS MILES2,
   CASE WHEN t2.MILES = t1.MILES AND t2.MILES != 9999 THEN t2.FLATRATE
        ELSE t3.RATEBASIS
   END AS RATE           
FROM TABLE1 AS t1
    LEFT JOIN TABLE2 AS t2 
        ON t1.[COMPANY] = t2.[COMPANYCODE] AND (t1.[MILES] = t2.[MILES])
    INNER JOIN (
         SELECT TOP 1 TRUCKERCODE, MILES, RATEBASIS, FLATRATE FROM TABLE2 WHERE MILES = 9999
               ) AS t3 
   ON t1.[COMPANY] = t3.[COMPANYCODE]

如果里程相同,我需要ON子句加入,然后得到匹配的给定字段,否则我需要从第二个表中获取的默认数据是里程等于9999.现在,当ON条款我得到许多额外的行,其中MILES等于45,它从TABLE2获取数据,其中里程等于45,所有数据的里程等于9999.我需要它做一个或另一个但不是两个。这就是我的表格看起来像

TABLE1                          TABLE2
ID COMPANY MILES ETC            ID COMPANYCODE MILES RATE
1  ILLINI  50                   1  ILLINI      50    3.2
2  ILLINI  110                  2  ILLINI      110   5.2
3  ILLINI  150                  3  ILLINI      150   2.4
4  ILLINI  200                  4  ILLINI      200   1.9
5  ILLINI  250                  5  ILLINI      9999  1.5
6  ILLINI  300                       
7  ILLINI  350
8  ILLINI  400
9  ILLINI  450
10 ILLINI  500

Desired Output
COMPANY MILES MILES2 RATE
ILLINI  50    50    3.2
ILLINI  110   110   5.2
ILLINI  150   150   2.4
ILLINI  200   200   1.9
ILLINI  250   9999  1.5
ILLINI  300   9999  1.5                    
ILLINI  350   9999  1.5
ILLINI  400   9999  1.5
ILLINI  450   9999  1.5
ILLINI  500   9999  1.5

2 个答案:

答案 0 :(得分:1)

我认为这会给你你想要的东西:

SELECT t1.COMPANY, t1.MILES,
       CASE WHEN t2.MILES IS NULL THEN t3.MILES
            ELSE t2.MILES
       END AS MILES2,
       CASE WHEN t2.MILES IS NULL THEN t3.RATE
            ELSE t2.RATE
       END AS RATE           
FROM TABLE1 AS t1
LEFT JOIN TABLE2 AS t2 
   ON t1.[COMPANY] = t2.[COMPANYCODE] AND (t1.[MILES] = t2.[MILES])
INNER JOIN (
   SELECT TOP 1 COMPANYCODE, MILES, RATE FROM TABLE2 WHERE MILES = 9999
) AS t3 
   ON t1.[COMPANY] = t3.[COMPANYCODE]    

如果MILES中匹配,则输出包含TABLE1TABLE2的两个记录。否则,输出包含左表中的记录,即TABLE1TABLE2中带有MILES = 9999特定记录。

请注意,TOP 1用于最后一个子查询,以防 MILES = 9999中存在TABLE2多个记录

<强>输出:

COMPANY MILES   MILES2  RATE
----------------------------
ILLINI  50      50      3,2
ILLINI  110     110     5,2
ILLINI  150     150     2,4
ILLINI  200     200     1,9
ILLINI  250     9999    1,5
ILLINI  300     9999    1,5
ILLINI  350     9999    1,5
ILLINI  400     9999    1,5
ILLINI  450     9999    1,5
ILLINI  500     9999    1,5

SQL Fiddle Demo here

答案 1 :(得分:0)

我会基于双左连接...一次匹配,如果没有,则默认为9999实例

SELECT
      T1.*,
      coalesce( T2.miles, T3.miles ) as Miles2,
      coalesce( T2.rate, T3.rate ) as MileageRate
   FROM
      TABLE1 T1
         LEFT JOIN TABLE2 T2
            on T1.Company = T2.CompanyCode
           AND T1.Miles = T2.Miles
         LEFT JOIN TABLE2 T3
            on T1.Company = T3.CompanyCode
           AND T3.Miles = 9999

确认工作at this SQL Fiddle link