SQL Server:如何在同一选择语句中使用列值

时间:2018-09-27 11:12:37

标签: sql-server

我有一个从多个表中获取值的查询,它看起来与下面的查询很相似。

我以粗体突出显示了我需要传递同一查询返回的值的地方。

 select E.[EmployeeName] as EmployeeName
, (select City from tblEmployeeCities where C.EmployeeID = E.EmployeeID) as EmployeeCity
, (Select State from tblStates **where City =  /i need to give the name of 
the city returned by the above statement**  ) as EmployeeState
from tblEmployees E

3 个答案:

答案 0 :(得分:1)

使用JOIN / LEFT JOIN:

SELECT E.EmployeeName, C.City, S.State
FROM tblEmployees E
LEFT JOIN tblEmployeeCities C ON C.EmployeeID=E.EmployeeID
LEFT JOIN tblStates S ON S.City=C.City

答案 1 :(得分:0)

也许像

select E.[EmployeeName] as EmployeeName
    , c.City as EmployeeCity
    , (Select State from tblStates where City = c.City ) as EmployeeState
from tblEmployees E
    inner join tblEmployeeCities C on C.EmployeeID = E.EmployeeID

答案 2 :(得分:0)

我认为这可以通过sql语句的select部分中的CASE WHEN ELSE END语句来实现。

在此处查看语法或用法示例:https://www.w3schools.com/sql/func_mysql_case.asp