How to fetch data from two different tables in SQL - sql

I'm trying to fetch the records from two different tables in the same database. But I encounter an error.
Query:
use AdventureWorks2014
select
cast(departmentID as nvarchar), ModifiedDate
from
[HumanResources].[Department]
union
select
LoginID, JobTitle
from
[HumanResources].[Employee]
Error:
Msg 241, Level 16, State 1, Line 2
Conversion failed when converting date and/or time from character string.
I appreciate your help.
Thanks All

Wild guess, but I am thinking that you are likely trying to get the records from the [HumanResources].[Employee] table and their corresponding department via the [HumanResources].[Department] table.
If this is the case, then I am assuming that there would be a key relationship between the tables. For example, your Employee table could have a DepartmentId column for which you can then perform a join.
Employee Table
LoginId
FirstName
LastName
JobTitle
DepartmentId
Department Table
DepartmentId
DepartmentName
ModifiedDate
Then for a table structure like above, you just need to make a JOIN operation on the table.
SELECT emp.LoginId, emp.FirstName, emp.LastName, dep.DepartmentName
FROM Employee emp
INNER JOIN Department dep ON dep.DepartmentId = emp.DepartmentId
If you can post your table structure and the desired data output, then I am pretty sure we could help you formulate the query better.

You used UNION, so the datatypes of the columns in both select statements should be the same.
And you are fetching the data from the Department and Employee table. Here, you have to use the join between Department and EmployeeDepartmentHistory on DepartmentID and join between EmployeeDepartmentHistory and Employee table on BusinessEntityID to get the columns you have posted.
SELECT
D.DepartmentID
,D.ModifiedDate
,E.LoginID
,E.JobTitle
FROM [HumanResources].[Department] D
INNER JOIN [HumanResources].[EmployeeDepartmentHistory] EDH
ON D.DepartmentID = EDH.DepartmentID
INNER JOIN [HumanResources].[Employee] E
ON EDH.BusinessEntityID = E.BusinessEntityID
Here is the sample:

Related

INNER JOIN and Count POSTGRESQL

I am learning postgresql and Inner join I have following table.
Employee
Id Name DepartmentId
1 John S. 1
2 Smith P. 1
3 Anil K. 2
Department
Department
Id Name
1 HR
2 Admin
I want to query to return the Department Name and numbers of employee in each department.
SELECT Department.name , COUNT(Employee.id) FROM Department INNER JOIN Employee ON Department.Id = Employee.DepartmentId Group BY Employee.department_id;
I dont know what I did wrong as I am new to database Query.
When involving all rows or major parts of the "many" table, it's typically faster to aggregate first and join later. Certainly the case here, since we are after counts for "each department", and there is no WHERE clause at all.
SELECT d.name, COALESCE(e.ct, 0) AS nr_employees
FROM department d
LEFT JOIN (
SELECT department_id AS id, count(*) AS ct
FROM employee
GROUP BY department_id
) e USING (id);
Also made it a LEFT [OUTER] JOIN, to keep departments without any employees in the result. And COALESCE to report 0 employees instead of NULL in that case.
Related, with more explanation:
Query with LEFT JOIN not returning rows for count of 0
Your original query would work too, after fixing the GROUP BY clause:
SELECT department.name, COUNT(employee.id)
FROM department
INNER JOIN employee ON department.id = employee.department_id
Group BY department.id; --!
That's assuming department.id is the PRIMARY KEY of the table, in which case it covers all columns of that table, including department.name. And you may want LEFT JOIN like above.
Aside: Consider legal, lower-case names exclusively in Postgres. See:
Are PostgreSQL column names case-sensitive?

issue with hierarchical queries in db2

I have the following tables
Lead
id varchar
employee_id varchar
Employee
id varchar
lead_id varchar
There will be a group of employees assigned to a lead. The Lead table holds the employee id of the lead.
The employee table will have lead_id which will be the id key of the leader.
The table will also contain employees which are not assigned to any lead
I need a query which will display the hierarchical result which will list the leaders and the employees under the leader
leader1 (employee )
employee1
employee 2
Leader 2(employee)
employee 3
employee 4
Any idea how this kind of hierarchical result can be obtained by a db2 query?
Click on the this link to view the table structure
The answer is a join of the two tables like
SELECT l.employee_id as leader_employee_id, e.id as employee_id
FROM LEAD l
INNER JOIN EMPLOYEE e
ON e.lead_id = l.employee_id

Query Multiple Columns Within a Table

I have a table of employees that are formatted as follows:
EMPLOYEE (FNAME,MINIT,LNAME,SSN(PK),BDATE,SUPERSSN(NULLABLE))
I need to query every employee and retrieve the following information:
FNAME(employee),LNAME(employee),SUPERSSN,(super)FNAME,(super)LNAME
UPDATED
After running this query:
SELECT A.FNAME,A.LNAME,A.SUPERSSN,B.FNAME,B.LNAME
FROM EMPLOYEE
A LEFT JOIN EMPLOYEE B
ON A.SUPERSSN = B.SSN;
The results were close, but when the superssn was null (CEO/Boss) it caused the remaining rows to populate as null also and did not populate with the actual supervisors ssn. I'm trying to use an IF statement to fix the problem with having a SuperSSN that is null, but I'm receiving the error: ORA-00905: missing keyword.
Below is the query that I ran that generated the error.
SELECT A.FNAME,A.LNAME,A.SUPERSSN,B.FNAME,B.LNAME
FROM EMPLOYEE A LEFT IF A.SUPERSSN <> 'NULL'
JOIN EMPLOYEE B ON A.SUPERSSN = B.SSN;
Select A.FName,
A.LNAme,
A.SuperSSN,
B.FName,
B.LName
from Employee A
Left Join Employee B
On A.SuperSSN = B.SSN

does anyone know how to list the empid and the name of all supervisors if supervisors are in employee table too?

I have a table that contains empid, name, salary, hiredate, position and supervisor (which includes empid, not the name). How do I list the empid and name of all supervisors?
The output has to have to columns supervisor (and a list of their empid) and their names. This is the create statement used to create the Employee table:
/* Create table Employee */
IF OBJECT_ID('Employee', 'U') IS NOT NULL
DROP TABLE Employee
GO
CREATE TABLE Employee (
emp_id NCHAR(5),
name NVARCHAR(20),
position NVARCHAR(20),
hire_date DATETIME,
salary MONEY,
bcode NCHAR(3),
supervisor NCHAR(5)
)
I have tried a variety of statements using having statement and count but they don't seem to work.
select emp_id, name from employee where position='manager';
I tried this but it doesn't work. Anyone smart that knows how to do it?
You will have to join the table back on itself:
select a.name, a.position, a.hiredate, a.salary, a.supervisorid,
isnull(b.name, '') as SupervisorName
from EmployeeTable a
left join EmployeeTable b
on a.SupservisorID=b.ID
The left join will make sure that the employees who do not have supervisors are returned, and isnull(b.name, '<NONE>') can be used if you would like to have something other than NULL as a value in those cases.
SELECT e.empid ,ISNULL(b.name, 'No supervisor') SupervisorName
FROM employee e LEFT JOIN employee b
ON e.supervisorid = b.empid
Inner join will leave out the people who do not have a supervisor , Use left join to get all the employees
If you want supervisors only, you just need to select rows whose emp_id values are found in the supervisor column:
SELECT
SupervisorID = emp_id,
SupervisorName = name
FROM dbo.Employee
WHERE emp_id IN (SELECT supervisor FROM dbo.Employee)
;

Deriving a column's data from a matching column in SQL

So I have a table that has, employee number, employee name, supervisor number.
I want to run a query that will retrieve employee name, employee number, supervisor name and supervisor number. Only one employee doesn't have a supervisor meaning it will have to display nulls. How would I do this? I'm using Oracle SQL Plus. My attempts haven't worked at all! Any help would be much appreciated.
SELECT ename Employee, empno Emp#, super Manager#
FROM emp;
That gets me three of the columns but to be honest I don't even know where to start to get the supervisors names.
It's for university, but I'm studying for a test it's not for an assignment so no cheating happening here :).
The following should work, and give you nulls if the employee has no supervisor:
SELECT empGrunt.ename Employee
, empGrunt.empno EmpNum
, empSuper.ename SupervisorName
, empSuper.empno SupervisorName
FROM emp empGrunt LEFT OUTER JOIN emp empSuper
ON empGrunt.super = empSuper.empno
Assuming that SupervisorNumber is a foreign key relationship back to the Employee table (where it's the EmployeeNumber of the supervisor's record), then you need to use an outer join.
What you need in this case is a left join:
select
e.EmployeeName,
e.EmployeeNumber,
s.EmployeeName as SupervisorName
from Employee e
left join Employee s on s.EmployeeNumber = e.SupervisorNumber