SQL查询无法正常使用多个连接子句

时间:2015-02-10 19:40:38

标签: sql sql-server

我一直在研究这个查询。我刚刚获得部分解决方案,现在尝试将该查询添加到我的大问题中,我在查询输出方面遇到了一些问题。

SELECT T1.[miles], 
       T2.[name], 
       T2.[code], 
       T2.[routesid], 
       T2.[id], 
       T2.[company], 
       T2.[contract], 
       T2.[supplier], 
       T3.[tons], 
       CASE 
         WHEN T4.miles IS NULL THEN T5.miles 
         ELSE T4.miles 
       END MILES2, 
       CASE 
         WHEN T4.miles = T1.miles 
              AND T4.miles != 9999 THEN T4.flatrate 
         ELSE T5.rate 
       END AS RATE, 
       T3.[change] 
FROM   ((table1 AS T1 
         JOIN table2 AS T2 
           ON T1.[company] = T2.[company] 
              AND T1.[id] = T2.[routesid]) 
        JOIN table3 AS T3 
          ON T1.[company] = T3.[code]) 
       LEFT JOIN table4 AS T4 
              ON T1.[company] = T4.[code] 
                 AND ( T1.[miles] = T4.[miles] ) 
       INNER JOIN (SELECT TOP 1 code, 
                                miles, 
                                rate, 
                                flatrate 
                   FROM   table4 
                   WHERE  miles = 9999 
                          AND active = 1) AS T5 
               ON T1.[company] = T5.[code] 
WHERE  T2.[active] = 1 
       AND T2.[expiration] < '02/10/2015' 
       AND T1.[miles] > 0 
       AND T1.[company] = 'COMPANY' 
       AND T3.[active] = 1; 

我知道这是一个大问题。我试图弄清楚为什么它会丢弃与表4中的里程数配对的数字,它与9999配对。打印出来没有问题。

MILES NAME CODE ROUTESID ID   COMPANY CONTACT SUPPLIER TONS MILES2 CHANGE
140   N/A  N/A  3425     185  ILLINI  TARIFF 1 N/A      24  140    Weekly
144   N/A  N/A  4532     198  ILLINI  TARIFF 3 N/A      24  144    Weekly
9999  N/A  N/A  2134     150  ILLINI  TARIFF 2 N/A      24  9999   Weekly

如果它符合下面这种情况,它现在不会打印出来。我从之前的堆栈溢出中获取了SQL语句,如果Miles和Miles2不匹配,我会打印SQL语句但是因为我将SQL添加到一起它就停止了工作。

MILES NAME CODE ROUTESID ID   COMPANY CONTACT SUPPLIER TONS MILES2 CHANGE
140   N/A  N/A  3420     170  ILLINI  TARIFF 4 N/A      24  9999   Weekly

Previous Stack Overflow

Here is a demo of the issue 如您所见,TABLE1中的250,300,350,400,450和500未显示。

Here is the resolution

1 个答案:

答案 0 :(得分:1)

Giorgos在您之前的Stack Overflow线程中给出的答案部分是因为您的示例中只有一家公司。查看查询的这一部分?:

INNER JOIN (SELECT TOP 1 code, 
                            miles, 
                            rate, 
                            flatrate 
               FROM   table4 
               WHERE  miles = 9999 
                      AND active = 1) AS T5 
ON T1.[company] = T5.[code] 

这实际上只取表中的顶行(其中miles = 9999且active = 1),然后尝试将其连接到T1表。不是每家公司的最高行,只是排在第一行。因此,当您将T5表加入公司字段的T1表时,无论公司恰好位于第一行,都是唯一可用的公司。您可以通过使用distinct而不是top 1来解决这个问题,如果表中没有多行代表单个代码,其中miles = 9999且active = 1(我猜你不应该这样,因为这意味着同一代码和里程有多种费率):

INNER JOIN (SELECT distinct code, miles, rate, flatrate 
            FROM   table4 
            WHERE  miles = 9999 AND active = 1
            GROUP BY code) AS T5 ON T1.[company] = T5.[code] 

但正如其他人所说,很难理解你想要完成什么,部分原因是你的查询格式很奇怪。这或许有助于重新解释您的表格的性质和您正在寻求的解决方案,以及更好地定义问题。