Creating a sentence from multiple tables in SQL - sql

I am trying to create this Result “Sabre is 12 years old” sentence using the code below in SQL.
select
businessname+' is ' + cast(count(e.id)as varchar(11))
from
Department d
join
EmployeeDepartmentHistory EDH on edh.departmentid = D.departmentid
join
employee e on edh.id = e.id
group by
name
+' years old'
If I were to run this section of the code
select
businessname+' is ' + cast(count(e.id)as varchar(11))
from
Department d
join
EmployeeDepartmentHistory EDH on edh.departmentid = D.departmentid
join
employee e on edh.id = e.id
group by
name
I will get "Sabre is 12"
But I am having a problem getting the "years old" string at the end.
I am getting this error message with the full code
Msg 8120, Level 16, State 1, Line 4
Column 'HumanResources.Department.Name' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

Without having some required information like:
The structure of the tables, which tables have what columns
How the tables are related to each other,
What you are trying to fetch (eg. what 'businessname' signifies here)
it becomes little difficult to provide proper suggestion.
So, assuming that:
EmployeeDepartmentHistory is the bridge table between Department
and Employee tables to take care of Many:Many relationship between
Department and Employee tables
One businessname (whichever table it belongs to) has
many employees (e.id) under it
You are trying to calculate the count of employees (e.id) for
each businessname,
This would be the right query:
SELECT businessname+' is ' + CAST(COUNT(e.id) AS VARCHAR(11)) + ' years old'
FROM Department d
JOIN EmployeeDepartmentHistory EDH on edh.departmentid=D.departmentid
JOIN employee e on edh.id=e.id
GROUP BY businessname

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?

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

Creating new columns from data in other columns based on primary key

7.1 List the employee name, employee title, manager name, and manager title for each employee.
Use clear column aliases for your results, and do not exclude any employees in your list.
I'm new to SQL so bear with me. I've managed to have the output list of every employee, their job title, and the employee ID of the employee of they report to (aka their manager). I can't for the life of me figure out how to properly add two additional columns (ManagerName and ManagerJobTitle) with the necessary correct information in it.
Here is my query so far.
Select (FirstName + ' ' + LastName) as EmployeeName, Title as JobTitle, ReportsTo
From Employees E
Order By ReportsTo
You didn't show any schema for your tables, but from your query I can see you are missing the join with the manager table, from where those two columns where probably supposed to come.
Edit: OK, now I get it. The employee table relates to itself. You didn't specified the PK for the table, so I'll assume the Employee has an Id. If the key is another column, just change it in the query below:
Select (E FirstName + ' ' + E.LastName) as EmployeeName,
E.Title as JobTitle,
(R.FirstName + ' ' + R.LastName) as 'ManagerName',
R.Title as 'ManagerTitle'
From Employees E
LEFT JOIN
Employees R ON E.ReportsTo = R.Id
Order By ReportsTo
Edit 2: Changed from INNER JOIN to LEFT JOIN, as a employee can have no manager.
Select (E.FirstName + ' ' + E.LastName) as EmployeeName, E.Title as JobTitle, mgr.ReportsTo, (mgr.FirstName + ' ' + mgr.LastName) as ManagerName, mgr.Title as MamagerJobTitle
From Employees E
Left join Employees mgr on E.EmployeeID = mgr.ReportsTo
Order By ReportsTo
Note: As per my understanding, ReportsTo column has employeeID who have report to any manger, if not please replace that column with mgr.ReportsTo

SQL Help for Beginner please

I am learning SQL at university. Stuck one a question and any help would be appreciated.
Question:
Write a SQL statement to retrieve the first and last name as a column “fullname” of the employees which manage 2 or more projects (2pts).
Background info:
EMPLOYEE Table with 2 entries, PROJECT Table with 4 project tables. Last column is ProjectManager which has the Employee ID. Two of the projects are managed by the same employee.
What I have:
Select EMPLOYEE.FirstName+','+EMPLOYEE.LastName AS FullName
FROM EMPLOYEE
WHERE count(PROJECT.ProjectManager==EMPLOYEE.EmployeeID) > 1
EDIT:
Sorry for the confusion guys. Its a PROJECT table with 4 records. I needed to find the first and last name of the Employee whose ID was listed under 2 different project records. The employee ID went in the ProjectManager column. The answer Serif Emek gave seems to be what I needed.
That may help;
Select E.FirstName+','+E.LastName AS FullName
FROM EMPLOYEE E, PROJECT P
WHERE
E.EmployeeId = P.ProjectManager
GROUP BY E.FirstName,E.LastName, E.EmployeeId
HAVING COUNT(*) > 1
Go with the ANSI standard version
SELECT e.FirstName + ',' + e.LastName AS FullName
FROM employee AS e
INNER JOIN project AS p
OM e.EmployeeId = p.ProjectManager
GROUP BY e.FirstName, e.LastName, e.EmployeeId
HAVING COUNT(*) >= 2;
See also: ANSI vs. non-ANSI SQL JOIN syntax