SQL Server : replace several instances of userID with username - sql

I may be overthinking this but I have not managed to figure it out or find a solution, so I'm hoping for a pointer in the right direction. I tried using the Select ColumnA AS Column B etc but it's not doing what I want.
I have 2 tables, scenario examples below
Table 1 (Vehicle)
VehicleID (001)
VehicleMake (Ford)
VehicleModel (Falcon)
VehicleExCleanEmpID (005)
VehicleIntCleanEmpID (003)
Table 2 (Employee)
EmpID (005)
EmpName (Dave)
The scenario being that a vehicle is cleaned internally or externally by any one of a pool of employees shown by the relevant ID in the Vehicles table.
I want to show in a query VehicleID, InsideCleanName, ExternalCleanName rather than showing the employee's ID.
So end up with results similar to this
VehicleID InsideCleanName ExternalCleanName
------------------------------------------------
001 Bob Dave
002 Sue Dave
003 John Sid
Thanks for any tips and or help

THat seems like a pretty simple query with two inner joins to the Employee table - something like this:
SELECT
v.VehicleId,
InsideCleanName = e1.EmpName,
ExternalCleanName = e2.EmpName
FROM
dbo.Vehicle v
INNER JOIN
dbo.Employee e1 ON v.VehicleIntCleanEmpId = e1.EmpID
INNER JOIN
dbo.Employee e2 ON v.VehicleExCleanEmpId = e2.EmpID
Joining to the Employee e1 table is giving you the employee who was responsible for the inside cleaning, while joining a second time, to Employee e2 gives you the one responsible for the external cleaning.

Join the two table with EmpId and select the columns you want similar to the code below:
select column1, column2 from table1 inner join table2 on table1.EmpId = table2.EmpId

Related

Return unique value in SQL when joining two tables

I have question, I have hard time in solving a question on how to actually joining two table using inner join, where the return value shown must only be the unique value on both table.
For example: if table A contains:
ID Name
-------------------
1 Andy
2 Anthony
3 Sandy
And table B:
ID Job
----------------------
1 Student
1 Entrepreneur
3 CEO
It will return only Sandy as CEO and not returning ANDY with both jobs as student and entrepreneur.
Thanks a lot for your time and attention.
A simple join and aggregation would seem to work here:
SELECT a.ID, MAX(a.Name) AS Name, MAX(b.Job) AS Job
FROM TableA a
INNER JOIN TableB b
ON b.ID = a.ID
GROUP BY a.ID
HAVING COUNT(*) = 1;
Demo
The logic here is that the inner join filters off person in the A table not having any match at all in the B table. For those which do have matches, we retain single job match only by checking the count.

SQL JOIN to get the compare two values/row from table "A" and the same row from table "B"

I have two tables with the following rows
Table A (transaction)
Order Seller Customer
1 300 500
Table B (Persons)
PersonID FullName
300 Peter White
500 Scott Bold
I want a result like this
Order Seller Customer FullName (Seller) FullName (customer)
1 300 500 Peter White Scott Bold
I've tried multiple things however which makes more sense is a join a table twice, however I'm getting:
Ambiguous column name
This is SQL Server 2019.
Basically I'm looking to retrieve info from the same table instead of creating additional tables. Is that possible? If yes, how do you do? Thank you in advance.
As #jarlh wrote in comment:
select t.order, t.seller, t.customer, sel.fullname, cust.fullname
from transaction t
join persons sel -- sel is an alias to persons table
on sel.personid = t.seller
join persons cust
on cust.personid = t.customer;
Query with join will return the result as long as both seller and customer exist in persons table -- here it should as source table names transactions :).
I have another form of query it still join table B twice.
This is archaic syntax which I don't recommend but for beginner know the concept of JOIN:
select t.*,B.FullName as FullName (customer) from
(
select A.Order,A.Seller,A.Customer,B.FullName as FullName(Seller)
from A,B where A.Seller=B.PersionID
) t, B where t.Customer=B.PersionID
The proper way of JOIN:
select t.*,B.FullName as FullName (customer) from
(
select A.Order,A.Seller,A.Customer,B.FullName as FullName(Seller)
from A JOIN B ON A.Seller=B.PersionID
) t JOIN B ON t.Customer=B.PersionID
Hoping this can help you.

How to create this append record?

I have a table full with employees structured as:
tblEmployees
+--------------+------------+-----------+-------+
| EmployeeID | FirstName | LastName | Wage |
+--------------+------------+-----------+-------+
I then have a table which the user can paste data into from an external software which looks like so:
tblImport
+------------+-----------+--------------+
| EmployeeID | WorkDate | HoursWorked |
+------------+-----------+--------------+
This will then go into another table (HoursWorkedRecords) which is structured the same way.
When I append from the import table to the main table what I would like is firstly:
The append to check if the EmployeeID pasted into the tblImport table exists in tblEmployees, if so then it append to HoursWorkedRecords.
Before importing check there are no duplicate records by the EmployeeID on that given WorkDate.
My question is how can I achieve this?
You can use a query to do this. If you use a LEFT JOIN between HoursWorkedRecords and tblEmployees on EmployeeID then any null entries in your employees table will signify hours worked records where the employee could not be found. You can either use this query directly or through a VBA module.
The (untested) SQL for the query is
SELECT
HWR.EmployeeID
FROM HoursWorkedRecords AS HWR
JOIN tblEmployees AS TE
ON HWR.EmployeeID = TE.EmployeeID
WHERE
TE.EmployeeID IS NULL
The answer to your question depends on how you wish to proceed should either of your requirements fail to be met:
What should happen if the EmployeeID is not found in the tblEmployees table?
What should happen if there are duplicates found in the HoursWorkedRecords table?
If the answer to these questions is to simply ignore the records which do not meet the criteria, then this can be achieved with a relatively simply INSERT query:
insert into hoursworkedrecords
select
i.employeeid, i.workdate, i.hoursworked
from
(tblimport i inner join tblemployees e on i.employeeid = e.employeeid)
left join hoursworkedrecords h on i.employeeid = h.employeeid and i.workdate = h.workdate
where
h.employeeid is null
Here, the inner join on the tblEmployees table ensures that the EmployeeID is valid, and the left join on the hoursworkedrecords table in conjunction with the is null criteria ensures that a record for that employee on that date does not exist.
If however, the user should be alerted to these issues, you should use the reverse of the above query to select the invalid records for the user to review before proceeding.

Joining same table multiple times

I have 2 tables Person an Department - where each person has multiple departments registered against him.
Person
id|name|dept1|dept2|dept3
1 |Jane|100 |102 |106
Dept
id |Name
100|Accounts
...
102|HR
...
106|Admin
Whats the most elegant sql to display Jane's record as follows:
Jane|Accounts|HR|Admin
Use this. And work on your naming convention to make all column names unique independent of table.
SELECT
Person.id, Person.name, dept1.Name, dept2.Name, dept3.Name
LEFT JOIN Dept dept1 ON dept1.id = Person.dept1
LEFT JOIN Dept dept2 ON dept2.id = Person.dept2
LEFT JOIN Dept dept3 ON dept3.id = Person.dept3
Something like this will let you join the same table multiple times. You just give each join a different alias
SELECT *
FROM Person AS P
INNER JOIN Dept AS D1 ON P.dept1 = D1.id
INNER JOIN Dept AS D2 ON P.dept2 = D2.id
WHERE P.name = 'Jane'
Ideally you would normalise the data in your Person table and have a linking table between Person and Dept e.g. PersonDepartmentLinking (or whatever convention you have for linking table naming conventions), assuming you have any control over the schema and it's possible to add the relationship that way.
You can use STUFF in this case
Select name,
Stuff((Select distinct ', ' + cast(Name as varchar(20))
From #Dept t2
Where t2.Id = t1.Id
FOR XML PATH('')),1,1,'')
From Person t1
The only way that I know is a join for each column.
But if you are in the way of designing the tables, i suggest you to normalize the DB.
If a person need an extra dept column, you need to alter the table to add a new property of person.
For me, 3 entities are needed:
- Person
- Department
- person_department_assignation

SQl to select from multiple tables

I have two table emptable1(empid,status) emptable2(empid,week)
i want to select all the empid whose status is 0 in emptable1 and from that list of empid i need to select empid whose week is 7 from the table emptable2
Please help :-)
Not knowing your table structure in detail, but this ought to work:
SELECT
(fields)
FROM
dbo.emptable1 e1
INNER JOIN
dbo.emptable2 e2 ON e1.empid = e2.empid
WHERE
e1.status = 0
AND e2.week = 7
How about using join? Join the two, then do your logic implementation altogether.