加入子查询

时间:2013-11-24 02:49:48

标签: sql oracle

Q 1:

 SELECT SUBSTR(o.first_name,1,1)||' '||o.last_name "NAME",
    FROM employees o
    WHERE o.salary >
    (SELECT AVG(i.salary)
    FROM employees i
    WHERE i.department_id =
    o.department_id)

我有一个department_id和department_name ||的部门表如何将它连接到此结果以显示子查询和dep名称的结果?

q2)在添加最后一行后抛出错误:为什么?

SELECT SUBSTR(first_name, 1, 1) || ' ' || last_name "Employee Name", department_id "Department Id", to_char(NULL) "Department Name", to_char(NULL) " City" 
FROM employees
UNION
SELECT to_char(NULL) "Employee Name" , department_id "Department ID", department_name "Department Name", to_char(NULL)" City" 
FROM departments
UNION 
SELECT to_char(NULL) "Employee Name" , to_char(NULL) "Department Id", to_char(NULL) "Department Name" ,to_char(NULL )"City"
FROM locations

1 个答案:

答案 0 :(得分:1)

对于您的第一个查询,请尝试:

SELECT SUBSTR(o.first_name, 1, 1) || ' ' || o.last_name "NAME",
  d.department_name "DEP NAME"
FROM employees o
INNER JOIN department d ON d.department_id = o.department_id
WHERE o.salary > (
    SELECT AVG(i.salary)
    FROM employees i
    WHERE i.department_id = o.department_id
    )

当此列不是CHAR时,您的错误最有可能是to_char(null) department_id

只需使用null

SELECT SUBSTR(first_name, 1, 1) || ' ' || last_name "Employee Name",
  department_id "Department Id",
  to_char(NULL) "Department Name",
  to_char(NULL) " City"
FROM employees    
UNION    
SELECT to_char(NULL) "Employee Name",
  department_id "Department ID",
  department_name "Department Name",
  to_char(NULL) " City"
FROM departments    
UNION    
SELECT to_char(NULL) "Employee Name",
  NULL "Department Id",     -- Replace to_char(null) with NULL
  to_char(NULL) "Department Name",
  city_name "City"    -- Add city_name column to get results different than NULL
FROM locations