内部联接别名不起作用

时间:2014-05-12 18:18:06

标签: sql tsql

我尝试比较两个不同表中的竞争代码,这两个表连接在每个表中的数字id上,一个表是固定的位置格式。我收到错误的'。'在第5行的T2.DSNumber之间

select 
    T1.SNumber, 
    T1.Racecode1, 
    T1.Race1 , 
    SUBSTRING(rec,1,6) as T2.DSNumber,
    SUBSTRING(rec,175,2) as T2.DSRaceCode1,
    SUBSTRING(rec,251,12) as T2.DSRaceText1
 from scerts  T1
 INNER JOIN DS2012 T2
 on T1.SNumber = T2.DSNumber
 where right(T1.SNumber,6) = T2.DSNumber and T1.Racecode1 <>T2.DSRaceCode1
    and  T1.FLAG = 'o'
    and year(cast(T1.DDate as date)) ='2012' 
    order by T1.SNumber

5 个答案:

答案 0 :(得分:2)

如果我没错,您使用的是SQL Server。在您的查询中,以下部分是错误的

SUBSTRING(rec,1,6) as T2.DSNumber,

应该是

SUBSTRING(rec,1,6) as DSNumber,
SUBSTRING(rec,175,2) as DSRaceCode1,
SUBSTRING(rec,251,12) as DSRaceText1

答案 1 :(得分:2)

其他人显然接近不同的答案,但你的问题是你的第二个表(T2)实际上并没有#34; DSNumber&#34;和&#34; DSRaceCode1&#34;因为你从子串组件中提取它们。因此,需要将这些子字符串引用应用于您的连接(或WHERE)。我已格式化为JOIN条件SQL格式。您不能像您尝试的那样将alias.column作为列名称,但是足够的信息可以为您提供适当的语法。

此外,对于将来,希望可以通过表结构更改应用于您拥有的内容,使用基于id的列进行连接,而不是进入&#34;合并&#34;单个字段会破坏您的性能,查询和支持下游。

select 
      T1.SNumber, 
      T1.Racecode1, 
      T1.Race1, 
      SUBSTRING(T2.rec,1,6) as DSNumber,
      SUBSTRING(T2.rec,175,2) as DSRaceCode1,
      SUBSTRING(T2.rec,251,12) as DSRaceText1
   from 
      scerts  T1
         INNER JOIN DS2012 T2
            on right(T1.SNumber,6) = SUBSTRING(T2.rec,1,6)
            AND T1.Racecode1 <> SUBSTRING(T2.rec,175,2)
 where 
        T1.FLAG = 'o'
    and year(cast(T1.DDate as date))

另外..从每个表中查看样本数据肯定会帮助那些试图回答你问题的其他人:)

答案 2 :(得分:0)

您可能应该从您提供列的别名中删除T2.。如果您确定需要它,那么您需要使用引号或括号来转义它:

select field as [test.test]
select field as 'test.test'

答案 3 :(得分:0)

之后

  

作为

您应该为字段定义别名,而不是字段itselft 您的查询可能是这样的

我认为你的表格结构为

T1 = SNNumber, RACECODE1 and RACE1
T2 = REC 

如果这是真的那么你可以使用

SELECT  
            SUBSTRING(T2.rec,1,6) as DSNumber, 
            SUBSTRING(T2.rec,175,2) as DSRaceCode1, 
            SUBSTRING(T2.rec,251,12) as DSRaceText1
FROM        scerts T1
INNER JOIN  DS2012 T2 ON T1.SNNumber = RIGHT(T2.rec,6)
WHERE       T1.racecode1 <>  SUBSTRING(T2.rec,175,2)
AND         T1.FLAG = 'o' 
AND         year(cast(T1.DDate as date)) ='2012' 
ORDER BY    T1.SNumber

希望这项工作

答案 4 :(得分:-1)

我为固定位置数据创建了临时表,然后进行了连接。这次它奏效了。我想我不能从固定位置提取数据并插入与Join语句相同的选择列中。

Select  
  SUBSTRING(rec,1,6) as DSNumber,
  SUBSTRING(rec,175,2) as DSRaceCode1,
  SUBSTRING(rec,251,12) as DSRaceText1
into #tDSdata
from DS2012

select 
   T1.SNumber, 
   T1.RACECODE1, 
   T1.RACE1 , 
   T2.DSNumber,
   T2.DSRaceCode1,
   T2.DSRaceText1
from scerts  T1
INNER JOIN #tDSdata T2
on right(T1.SNumber,6) = T2.DSNumber
WHERE t1.racecode1 <> T2.DSRaceCode1
   and  T1.FLAG = 'o'
   and year(cast(T1.DDate as date)) ='2012' 
order by T1.SNumber