尝试在SQL Server查询中联接表时为什么出现错误

时间:2019-01-05 00:45:18

标签: sql sql-server-2012

我在下面编写了查询,以收集与卡车司机收入有关的数据。主查询和联接查询都可以正常工作。但是,当我将它们结合在一起时,会出现错误

  

Msg 4104,第16级,状态1,第37行
  无法绑定多部分标识符“ tn.ctripnumber”

> x <- seq(1:10) > x[5] <- 4 > y <- (seq.int(1,19,2)) > > x<- cbind(x,y) > x x y [1,] 1 1 [2,] 2 3 [3,] 3 5 [4,] 4 7 [5,] 4 9 [6,] 6 11 [7,] 7 13 [8,] 8 15 [9,] 9 17 [10,] 10 19 > > z <- x[1:4,] > y <- x[6:10,] > > z <- rbind(z,y) > z x y [1,] 1 1 [2,] 2 3 [3,] 3 5 [4,] 4 7 [5,] 6 11 [6,] 7 13 [7,] 8 15 [8,] 9 17 [9,] 10 19 > > df1 <- z[z[,1] %in% x[,1]] > > matrix(df1,9,2) # As expected I'm getting 9 rows [,1] [,2] [1,] 1 1 [2,] 2 3 [3,] 3 5 [4,] 4 7 [5,] 6 11 [6,] 7 13 [7,] 8 15 [8,] 9 17 [9,] 10 19 > > # Now I want to know what is the value inside the missing row > df2 <- z[!z[,1] %in% x[,1]] > > matrix(df2,1,2) # I'm getting NA and NA, bu I was expecting the values 4 and 9 [,1] [,2] [1,] NA NA 有关。我已经尝试过使用收益表名称以及tRev别名。

tRev.ctripnumber = tn.ctripnumber

2 个答案:

答案 0 :(得分:3)

这是您的from子句:

from tripnumber tn,
     tripresources tr join
     (select r.ctripnumber, sum(Revenue_Subtotal) as "Revenue" 
      from (select r.ctripnumber, r.cmethod, sum(r.curevenue) as Revenue_Subtotal
            from revenuedtl r 
            where r.cmethod in (select distinct r.cmethod from revenuedtl r)
            group by r.ctripnumber, r.cmethod
           ) r
    --where r.cmethod like 'BROK%'
      group by r.ctripnumber
     ) tRev
     on tRev.ctripnumber = tn.ctripnumber

简单规则:从不FROM子句中使用逗号。 始终使用正确的,明确的,标准 JOIN语法。

因此,请使用适当的JOIN重写此内容:

from tripnumber tn join
     tripresources tr
     on tn.ctripnumber = tr.ctripnumber join
     (select r.ctripnumber, sum(Revenue_Subtotal) as "Revenue" 
      from (select r.ctripnumber, r.cmethod, sum(r.curevenue) as Revenue_Subtotal
            from revenuedtl r 
            where r.cmethod in (select distinct r.cmethod from revenuedtl r)
            group by r.ctripnumber, r.cmethod
           ) r
    --where r.cmethod like 'BROK%'
      group by r.ctripnumber
     ) tRev
     on tRev.ctripnumber = tn.ctripnumber

您的错误将消失。

查询失败的技术原因是,的范围规则与CROSS JOIN不同。您实际上可以用CROSS JOIN替换逗号来解决此问题。但是正确的解决方案是正确表达您的联接。

答案 1 :(得分:2)

这是注释部分不适合的注释。尽量不要将老式的JOIN与现代Join混合使用。这使得阅读和调试更加困难。

例如,更改此内容

from tripnumber tn,tripresources tr
where tn.ctripnumber = tr.ctripnumber

对此:

from tripnumber tn
join tripresources tr on tn.ctripnumber = tr.ctripnumber