有没有办法使用" As"来连接表格?列名称

时间:2018-05-21 15:32:15

标签: sql sql-server join matching spaces

我正在尝试创建一个基于First Name和last Name将2个表连接在一起的查询。我成功地获得了我的子串,将名称从一列拆分为2名,命名为FirstName和LastName。这应该让我匹配这些列,以便他们可以获得正确的扩展名,电话号码,部门和名称。但是我在这里做错了。我这样做的方法不起作用,否则会引发错误。

SELECT SUBSTRING(Users.Names, CHARINDEX(' ', Users.Names + ' ') + 1, 8000)AS LastName, SUBSTRING(Users.Names, 1, CHARINDEX(' ', Users.Names) - 1) AS FirstName,Users.Extension, GA.[First], GA.[Last], GA.Department, GA.Phone, GA.Mobile
FROM GlobalAddress AS GA 
    Left Join Users ON GA.[First] = substring(Users.Names,1,charindex(' ',Users.Names) ) AND SUBSTRING(Users.Names, CHARINDEX(' ', Users.Names + ' ') + 1, 8000) = Ga.[Last]
WHERE GA.[Last] IS NOT NULL
ORDER BY Users.Extension

我的想法是我可以换掉左连接:

Users ON GA.[First] = FirstName AND Ga.[Last] = LastName

但是这会引发错误。列名称无效' FirstName'。

An example of the format i'm following

任何帮助将不胜感激。

编辑:The problem is that the first few people are not properly getting the extension and for some reason their names are not being split up. The issue isn't with the data on the table though

Edit2:An Example Of Global Addresses Table

An Example of Users

3 个答案:

答案 0 :(得分:1)

因此,您希望为列创建别名,因为它们的冗长主体出现在很多地方。交叉申请可以这样做:

SELECT
    q.LastName,
    q.FirstName,
    Users.Extension, GA.[First], GA.[Last], GA.Department, GA.Phone, GA.Mobile
FROM 
Users
cross apply (select
    SUBSTRING(Users.Names, CHARINDEX(' ', Users.Names + ' ') + 1, 8000)AS LastName,
    left(Users.Names, CHARINDEX(' ', Users.Names + ' ') - 1) AS FirstName
    )q
Right Join GlobalAddress AS GA 
    ON GA.[First] = q.FirstName 
    AND q.LastName = Ga.[Last]
WHERE GA.[Last] IS NOT NULL ORDER BY Users.Extension

当CROSS APPLY中没有FROM时,可以将其视为为其列创建别名。

答案 1 :(得分:0)

在加入时使用原始值 - 而不是别名

...Users ON GA.[First] = SUBSTRING(Users.Names, 1, CHARINDEX(' ', Users.Names) - 1)  ...

答案 2 :(得分:0)

哇。这可能是我第一次认为right join是更简单的做事方式:

SELECT v.LastName, v.FirstName, u.Extension, GA.[First], GA.[Last],
       GA.Department, GA.Phone, GA.Mobile
from Users u cross apply
     (values (substring(u.Names, CHARINDEX(' ', u.Names + ' ') + 1, 8000),
              left(u.Names, CHARINDEX(' ', u.Names + ' ') - 1)
             )
     ) v(LastName, Firstname) right join
     GlobalAddress GA
     on GA.[First] = v.firstname and
        Ga.[Last] = v.lastname
where GA.[Last] is not null
order by u.Extension;

我想知道你是否真的想要一个外连接。请注意,您可以使用left join和括号执行此操作。