SQL无效的列名

时间:2017-08-23 19:54:11

标签: sql sql-server

当我进行左连接时,我收到错误“无效的列名'FirstPart'”。

我知道我的专栏是别名,但我不知道该怎么做:

https://www.example.org/ Redirecting to www (yes)
http://www.example.org/ Redirecting to www (yes)
https://example.org/ Redirecting to www (no) This is the problem url
http://example.org/ Redirecting to www (yes)

3 个答案:

答案 0 :(得分:5)

如果您将整个内容包装在外部查询中,那么您的别名将可用,但由于您与别名处于同一级别,因此需要使用相同的逻辑再次派生它:

Select  

  h.Type,
  a.name,
  CASE 
    WHEN a.name LIKE '%-%' THEN LEFT(a.name, Charindex('-', a.name) - 1) 
    ELSE a.name
  END as FirstPart,
  CASE
    WHEN a.name LIKE '%-%' THEN RIGHT(a.name, Charindex('-', Reverse(a.v)) - 1)
  END as LastPart
from Table1 a
  left join Table2 h 
    on CASE WHEN a.name LIKE '%-%' THEN LEFT(a.name, Charindex('-', a.name) - 1) ELSE a.name END = h.ID

如果你包装了这个,你可以通过子查询引用:

select * 
from 
 (Select h.Type, a.name,
  CASE WHEN a.name LIKE '%-%' THEN LEFT(a.name, Charindex('-', a.name) - 1) ELSE a.name END as FirstPart,
  CASE WHEN a.name LIKE '%-%' THEN RIGHT(a.name, Charindex('-', Reverse(a.v)) - 1) END as LastPart
  from Table1 a ) inn
left join Table2 h 
  on inn.FirstPart = h.ID

作为旁注,如果您可以避免like匹配的加入,那么您将获得更好的效果。

答案 1 :(得分:0)

您可以使用子查询来使用别名

SELECT h.type, 
       a.name,
       a.firstpart,
       a.lastpart
  FROM (SELECT name,
               CASE WHEN name LIKE '%-%' 
                    THEN LEFT(name, CHARINDEX('-', name) - 1) 
                    ELSE name 
                END AS firstpart,
               CASE WHEN name LIKE '%-%' 
                    THEN RIGHT(name, CHARINDEX('-', REVERSE(v)) - 1) 
                END AS lastpart
          FROM table1
        ) a
   LEFT JOIN table2 h 
     ON a.firstpart = h.id

答案 2 :(得分:0)

SQL Server提供第四个选项(在重复表达式,使用子查询或使用CTE之后)。 。 。 apply。这很好,因为你可以"筑巢"表达式,而不必越来越多地缩进代码:

Select h.Type, a.name, FirstPart, LastPart
from Table1 a cross apply
     (values (CASE WHEN a.name LIKE '%-%' THEN LEFT(a.name, Charindex('-', a.name) - 1) ELSE a.name END,
              CASE WHEN a.name LIKE '%-%' THEN RIGHT(a.name, Charindex('-', Reverse(a.v)) - 1) END)
     ) v(First_part, LastPart) left join
     Table2 h
     on v.FirstPart = h.ID;