SQL Query根据条件从两个表中选择Multiple Column

时间:2011-10-04 11:39:54

标签: sql

我分别有两个表Table_EmployeeTable_Department,我想选择属于员工的经理超过三次&也希望随之显示粪便名称。

此任务必须在单个查询中完成。做起来容易吗? 这是我的表结构。

这里Column_Empno将是Column_Manager,这意味着该表是自引用

 Table_Employee

Column_Empno     int
Column_Fname     varchar(50)
Column_Lname     varchar(50)
Column_Job       varchar(50)
Column_Manager   int
Column_HireDate  date
Column_Salary    int
Column_Commision int
Column_DeptNo    int

 Table_Department 

Column_DeptNo    int
Column_Dname     varchar(50)
Column_Location  varchar(50)

2 个答案:

答案 0 :(得分:8)

经理+部门:

SELECT Column_Fname, Column_Lname, table_Department.Column_Dname
FROM Table_Employee
INNER JOIN table_Department ON Table_Employee.Column_DeptNo = table_Department.Column_DeptNo

或者你也可以写:

SELECT Column_Fname, Column_Lname, table_Department.Column_Dname
FROM Table_Employee
WHERE Table_Employee.Column_DeptNo = table_Department.Column_DeptNo

没有经过测试。 顺便说一句,为什么你将你的Colums命名为“Column _...”而不仅仅是“Fname”,“Lname”,......以及你的表“Table _....”而不仅仅是“Employee”和“Department” ?

答案 1 :(得分:5)

select
    t1.column_manager,
    t2.column_dname
from
(
    select column_manager, column_deptno = max(column_deptno)
    from table_employee
    group by column_manager
    having count(*) > 3
) t1
join table_department t2 on t1.column_deptno = t2.column_deptno