Query Multiple Columns Within a Table - sql

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

Related

Update column in table2 based on select query which contains count() from table1 using postgresql

Tables
Need to update department table's dcount column based on number of employees working in each department from employee table's dno column.
Tried using
update department set dcount=(select count() from employee INNER JOIN department ON employee.dno=department.dnumber group by dno);*
which gave an error : more than one row returned by a subquery used as an expression
Desired result is:
**dname|dnumber|dcount
Research|5|4
Admin|4|3
Headquarters|1|1**
Need help please.
Thanks in advance.
Gruheeth
Your subquery (select count() ...) returns several rows, one per employee, where postgres expect only one row from this subquery in order to update one row at a time in the department table. In this case, you case use a cte instead :
WITH list AS
(
select dno, count(*) AS dno_count
from employee
group by dno
)
update department AS d
set dcount = l. dno_count
from list AS l
where d.dnumber = l.dno ;

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?

How to fetch data from two different tables in 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:

SELECT Statement with correlated/nested Subquery

I have two tables in my database, Department & DepartmentErrors.
The DepartmentErrors table contains a column called 'Error
I would like to run a select statement on the Department table, matching any related occurrences of that department within DepartmentError, where the Error value matches a number. I would then like to append a column onto that result set, for each department, containing how many rows matching that department ID & Error value have appeared within the department error table. This is my code so far:
SELECT DISTINCT
Department.DeptID,
Name,
Size,
Location,
(
SELECT COUNT(*)
FROM DepartmentErrors
INNER JOIN Departments ON DepartmentErrors.DeptID = Departments.DeptID
WHERE Error = 2
) AS ErrorCount
FROM Departments
INNER JOIN DepartmentErrors ON Departments.DeptID = DepartmentErrors.DeptID
WHERE DepartmentErrors.Error = 2
Try this one -
SELECT d.DeptID,
d.Name,
d.Size,
d.Location,
e.ErrorCount
FROM Departments d
JOIN (
SELECT DeptID, ErrorCount = COUNT(*)
FROM DepartmentErrors
WHERE Error = 2
GROUP BY DeptID
) e ON d.DeptID = e.DeptID

Replacing a table value with the previous expression in oracle

Ok so I am having the following scenario
I have a table called employees and have to replaced the last names for some of the people there under the following conditions:
1-The last name must be replaced only to those employees who work on Oxford.
2-Their new last name is going to be the last name of the person that has their employee number -1 ( for instance employee#173 should have now employee#172 last name instead)
This is how I started the query:
select last_name,num_emp
from employees
where num_emp in(
select e.num_emp
from employees
join departments using(num_dept)
join office using(id_office)
where city='Oxford')
And I did a second query to make sure which values were going to replace which
Select last_name,num_emp
from employees
where num_emp in(
select (e.num_emp-1)
from employees
join departments using(num_dept)
join office using(id_office)
where city='Oxford')
Now I thought I could do this and make the code work... but it didn't:
update employees
set last_name=(select last_name
from employees
where num_emp in(
select (e.num_emp-1)
from employees
join departments using(num_dept)
join office using(id_office)
where city='Oxford')
Got error saying unexpected end of SQL command...
So I thought on making a change because I believed having too many values on the set was not the point and here is how I did it for last time:
update employees
set last_name=(select last_name
from employees)
where num_emp =(
select (e.num_emp-1)
from employees
join departments using(num_dept)
join office using(id_office)
where city='Oxford')
Got an error that says is missing right parenthesis, which I know it does not express whaat the issue is. I know I am missing something and part of the sintaxis is wrong as well as I may need to créate another table and add those values so that they get saved there and I can compare them with the original ones, but at this point I am totally blocked and can't discover what is the mistake I am doing. Please help me I'd really apprecciate it!
You are getting confused with what to update and what to update with in your statements.
Here is what to update. I use IN clauses to make it plain. An EXISTS clause would also be appropriate.
update employees
set last_name = ...
where num_dept in
(
select num_dept
from departments
where id_office in
(
select id_office
from office
where city = 'Oxford'
)
);
And here is what to update with:
set last_name =
(
select last_name
from employees prev_employee
where prev_employee.num_emp = employee.num_emp - 1
)
You should use the analytical lag function, then you also fill in gaps if for example employee 172 doesn't exist and you have to put the name of employee 171 in 173.
Your select should be something like this
with new_emp as
(select last_name,lag(last_name, 1, 0) over (order by num_emp) as new_last_name, num_emp
from employees)
select *
from new_emp
where num_emp in(
select e.num_emp
from employees e
join departments using(num_dept)
join office using(id_office)
where city='Oxford');
This select will give you the original last name, new last name, employee number.
Then afterwards your update should be this:
update employees x
set last_name = (with new_emp as
(select last_name,lag(last_name, 1, 0) over (order by num_emp) as new_last_name, num_emp
from employees)
select new_last_name
from new_emp ne
where ne.num_emp = x.num_emp)
where x.num_emp in(
select e.num_emp
from employees e
join departments using(num_dept)
join office using(id_office)
where city='Oxford');