简体   繁体   中英

How to add subquery as a column in SQL

How do I add a subquery as a column in my SQL script?

eg

Select emp_no, name,gender ,
    (select department_name from departments where employees.emp_no = departments.emp_no)
from employees

PS: I'm using oracle 8

Going by the semantics, what I understand is that you want an employee's department name to be shown alongside his/her other information. I would suggest you do a join instead:

Select emp_no, name, gender, department_name
from employees emp, departments dept
where emp.emp_no = dept.emp_no;

That looks reasonably sound, I would suggest some (possible typos) cleaning up: add a comma after "gender" and declare the table names, also set the subquery alias

Select employees.emp_no, employees.name, employees.gender,  
    (select departments.department_name from departments where employees.emp_no = departments.emp_no) as dept_name
from employees

Alternatively, a nice join would would work too, if the other data is feasible:

Select employees.emp_no, employees.name, employees.gender,  departments.department_name
from employees
inner join departments on employees.emp_no = departments.emp_no

left join is the best-practice, and should be faster in performance:

Select e.emp_no, e.name, e.gender , d.department_name
from employees e left join departments d on e.emp_no = d.emp_no;

You seem to be missing comma after gender.

Select emp_no, name,gender ,
(select department_name from departments     where employees.emp_no = departments.emp_no) as dept_name from employees

The below is what you need. Just added a comma after gender. This subquery would need to return only one row for each result as well or else an error will be seen.

Select emp_no, name,gender, 
    (select department_name from departments where employees.emp_no = departments.emp_no)
from employees

This query is your answer but it will work only if there is one column mentioned in that if we use more than one column than it will retrun an error .

"Select employee_id,first_name,
    (select department_name,manager_id from departments where employees.department_id = departments.department_id) as new_column
from employees;"

can you try this:

SELECT em.emp_no, em."name",em.gender , (SELECT distinct dp.department_name FROM departments dp WHERE em.emp_no = dp.emp_no) my_sub FROM employees em

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM