I have two tables. Employee Information and Skills
Employee Information has the following details - ID (Unique Identifier), FirstName, LastName.
Skills has the following details - Employee Id, Skillset
A sample data will be as follows:
Employee Information
Id FirstName LastName
1 John Connor
2 Thomas Anderson
Skills
EmployeeId Skillset
1 CRM
1 SQL Server 2000
1 .NET 3.5
2 Java
2 Hibernate
I need my output as follows:
1 John Connor CRM, SQL Server 2000, .NET 3.5
2. Thomas Anderson Java, Hibernate
I run SQL Server 2000. Is there anyway, that I can do this with the help of a query rather than use cursors.
No, there is no way to do this with just a single SQL statement. You could do it with cursors, but it would probably be easiest to just do it in your application code.
Related
I have a table that contains data like below:
Name
ID
Dept
Joe
1001
Accounting
Joe
1001
Marketing
Mary
1003
Administration
Mary
1009
Accounting
Each row is uniquely identified with a combo of Name and ID. I want the resulting table to combine rows that have same Name and ID and put their dept's together separated by a comma in alpha order. So the result would be:
Name
ID
Dept
Joe
1001
Accounting, Marketing
Mary
1003
Administration
Mary
1009
Accounting
I am not sure how to approach this. So far I have this, which doesn't really do what I need:
SELECT Name, ID, COUNT(*)
FROM employees
GROUP BY Name, ID
I know COUNT(*) is irrelevant here, but I am not sure what to do. Any help is appreciated! By the way, I am using PostgreSQL and I am new to the language.
Apparently there is an aggregate function for string concatenation with PostgreSQL. Find documentation here. Try the following:
SELECT Name, ID, string_agg(Dept, ', ' ORDER BY Dept ASC) AS Departments
FROM employees
GROUP BY Name, ID
Looking around in the (now-discontinued) documentation and found this example:
Subquery in FROM clause
A subquery in a FROM clause acts similarly to a temporary table that is generated during the execution of a query and lost afterwards.
SELECT Managers.Id, Employees.Salary
FROM (
SELECT Id
FROM Employees
WHERE ManagerId IS NULL
) AS Managers
JOIN Employees ON Managers.Id = Employees.Id
(Excerpted from Subqueries - Subquery in FROM clause. The original author was Phrancis. Attribution details can be found on the contributor page. The source is licenced under CC BY-SA 3.0 and may be found in the Documentation archive. Reference topic ID: 1030 and example ID: 3327.)
My question is:
why using an extra ManagerId. An Id column is already in
Employees table,
why have the extra ManagerId to be null for a manager (ok it wants to be a joke).
My opinion:
despite the upvotes, something is wrong with this is example,
Tables with example data would be nice to see on the fly how it's working. One table with start data, one table temporary SELECT and one table the
resultset.
Edit: Thanks to all contributors for their answers!
#Alex K.: That is my point of view "it is not something one would actually use". But people, who wants to learn SQL, might think, that it is good practice, because it is in the documentation here.,
#Nebi: Thanks for the point that one would write it simpler to get the same result.
#Unnikrishnan R: "showcase how the sub query works" does in my eyes not only mean that it is fully functional but additional that it makes sense. If I get things simpler, why doing it the errorprone hard way.
#me: should have titled it "let's discuss sql documentation" or like that ;)
Let us consider a situation where Employee table holds all employees including their managers in which employee has an Id, and there is also a column for the manager Id (which can be null). This can be the point of view ,who was writing that SQL queries.
For Example,
+----+-------+--------+-----------+
| Id | Name | Salary | ManagerId |
+----+-------+--------+-----------+
| 1 | Joe | 70000 | 3 |
| 2 | Henry | 80000 | 4 |
| 3 | Sam | 60000 | NULL |
| 4 | Max | 90000 | NULL |
+----+-------+--------+-----------+
why have the extra ManagerId to be null for a manager --
getting the employees that are not managers
It is just an example how to do/ use Subqueries.
To your questions:
why using an extra ManagerId. An Id column is already in Employees
table
First of all ManagerId and Id are different columns of the table Employees. So there is a difference between them. But you might reffering to the Id of the Subquery Managers and the Id of the joined table Employees.
Then you need to define which Id you are using. Else you get the Error for ambigiuos column. In this example you to specify either the Subqueries Id which is Managers.Id or the Id of the joined table Employees (Employees.Id). Which one you choose is totally regardless because you use INNER JOIN one the Id.
why have the extra ManagerId to be null for a manager (ok it wants
to be a joke).
This is because of getting all the Employees that have are not managers. You are right about saying this could be done easier or in other form. For instance:
SELECT Id, Salary
FROM Employees
WHERE ManagerId IS NULL
This probably gets the same result as in the original. But the example is not about that, it is about the structure of a subquery.
why using an extra ManagerId. An Id column is already in Employees table
Consider you are having an employee table and you also wanted to keep the manager information in the same table.so apart from the ID column you need to add another column to keep the managerid.
why have the extra ManagerId to be null for a manager (ok it wants to be a joke).
The query is just to showcase how the sub query works. In this case subquery retrieves the manager from the Employee table (managerID is null) then join those id's with Employee table in the outer query to get the salary of each managers.
I'm trying to write an oracle SQL query that returns a single column containing values from multiple columns.
I have a table named CLIENT
clientid firstname Lastname
1 Steve Smith
2 James Hill
I want to return a single column "ALL" like so:
ALL
1
2
Steve
James
Smith
Hill
Is there a simple way to write this query?
This involves UNION
SELECT ClientID AS [All]
FROM Client
UNION ALL
SELECT FirstName
FROM Client
UNION ALL
SELECT LastName
FROM Client
I'm supposed to answer this for class, and it's tricky (for me)
Write a SELECT query to output the name of all employees with the name of their supervisor. If the employee has no supervisor, the supervisor name column should contain the text 'No Supervisor'.
The primary key field in my db is the employeeid and they are provided with names, and each student also has a supervisorid
The table for this is shown below (sorry for the layout):
employeeid lastname firstname salary supervisorid
1 Stolz Ted 25000 NULL
2 Boswell Nancy 23000 1
3 Hargett Vincent 22000 1
4 Weekley Kevin 22000 3
5 Metts Geraldine 22000 2
6 McBride Jeffrey 21000 2
7 Xiong Jay 20000 3
I was wondering how I could go about this statement without using the case statement to apply each of the 7 students with:
when concat(firstname,' ',lastname)='Nancy Boswell' then 'Ted Stolz'
In larger tables this would simply be a HUGE statement, is there a better way to do it?
Thanks!
EDIT:
I've now tried this:
SELECT
EMP1.employeeid as 'employee',
EMP2.supervisorid as 'manager'
FROM
employee EMP1
LEFT OUTER JOIN
employee EMP2
ON
emp1.employeeid = emp2.supervisorid;
However, I am seeing duplicate fields, for some reason employee 2 and 3 are appearing twice, meaning there are 9 fields showing instead of 7.
Also, I need to display their names, not their id's does that mean I need to join the join that i've already done to the employee name ? How would I do this?
Thanks for the feedback guys!
You need to link the table with itself based on the supervisorId. This might be strange if you are new to SQL but it is very common to do. You tell with SQL to add the row of the supervisor to the row of the employee via its primary key.
SELECT
*
FROM
EMPLOYEES EMP1
LEFT OUTER JOIN
EMPLOYEES EMP2
ON
-- make link between tables here
Note that the above query is not 100% correct / complete, its an indication. The LEFT OUTER JOIN statement makes the employees without supervisor have null values for the supervisor, otherwise the whole record would be left out.
I have an Access database that has two tables that are related by PK/FK. Unfortunately, the database tables have allowed for duplicate/redundant records and has made the database a bit screwy. I am trying to figure out a SQL statement that will fix the problem.
To better explain the problem and goal, I have created example tables to use as reference:
alt text http://img38.imageshack.us/img38/9243/514201074110am.png
You'll notice there are two tables, a Student table and a TestScore table where StudentID is the PK/FK.
The Student table contains duplicate records for students John, Sally, Tommy, and Suzy. In other words the John's with StudentID's 1 and 5 are the same person, Sally 2 and 6 are the same person, and so on.
The TestScore table relates test scores with a student.
Ignoring how/why the Student table allowed duplicates, etc - The goal I'm trying to accomplish is to update the TestScore table so that it replaces the StudentID's that have been disabled with the corresponding enabled StudentID. So, all StudentID's = 1 (John) will be updated to 5; all StudentID's = 2 (Sally) will be updated to 6, and so on. Here's the resultant TestScore table that I'm shooting for (Notice there is no longer any reference to the disabled StudentID's 1-4):
alt text http://img163.imageshack.us/img163/1954/514201091121am.png
Can you think of a query (compatible with MS Access's JET Engine) that can accomplish this goal? Or, maybe, you can offer some tips/perspectives that will point me in the right direction.
Thanks.
The only way to do this is through a series of queries and temporary tables.
First, I would create the following Make Table query that you would use to create a mapping of the bad StudentID to correct StudentID.
Select S1.StudentId As NewStudentId, S2.StudentId As OldStudentId
Into zzStudentMap
From Student As S1
Inner Join Student As S2
On S2.Name = S1.Name
Where S1.Disabled = False
And S2.StudentId <> S1.StudentId
And S2.Disabled = True
Next, you would use that temporary table to update the TestScore table with the correct StudentID.
Update TestScore
Inner Join zzStudentMap
On zzStudentMap.OldStudentId = TestScore.StudentId
Set StudentId = zzStudentMap.NewStudentId
The most common technique to identify duplicates in a table is to group by the fields that represent duplicate records:
ID FIRST_NAME LAST_NAME
1 Brian Smith
3 George Smith
25 Brian Smith
In this case we want to remove one of the Brian Smith Records, or in your case, update the ID field so they both have the value of 25 or 1 (completely arbitrary which one to use).
SELECT min(id)
FROM example
GROUP BY first_name, last_name
Using min on ID will return:
ID FIRST_NAME LAST_NAME
1 Brian Smith
3 George Smith
If you use max you would get
ID FIRST_NAME LAST_NAME
25 Brian Smith
3 George Smith
I usually use this technique to delete the duplicates, not update them:
DELETE FROM example
WHERE ID NOT IN (SELECT MAX (ID)
FROM example
GROUP BY first_name, last_name)