SQL Join using multiple tables - sql-server

I'm using the version of SQL Server which comes with Visual Studio 2017 and trying to create a view by joining columns from four tables which are as follows:
Table1: Employee (EmpID, EmpName, EmpContact, EmpSalary)
Table2: Customer (CustID, CustName, CustContact, CustEmail)
Table3: Orders (OrderID, OrderCustID, OrderDate, OrderStatus, OrderValue)
Orders.OrderCustID is foreign key which relates to Customer.CustID
Table4: Job (JobID, JobOrderID, JobEmpID, JobStatus, JobRemarks)
Job.JobOrderID and Job.JobEmpID are two foreign keys which relate to Orders.OrderID and Employee.EmpID respectively.
Now, I want to perform a join which will show all records of Orders table along with matches from other tables in following order:
OrderID, JobStatus, OrderStatus, CustID, CustName, CustContact, CustDue, EmpID, EmpName, EmpContact, Oredrvalue
Someone please help me write the SQL Query to perform the join. Many thanks in advance.

You need to walk through each JOIN to figure out what to join where. In other words, how do you get from Employees to Customers? It's just a logical walk-through.
Here's one approach, using inner joins (basically a big intersection of sets).
SELECT OrderID, JobStatus, OrderStatus, CustID, CustName, CustContact, CustDue, EmpID, EmpName, EmpContact, OrderValue
FROM Job
INNER JOIN Orders
ON Orders.OrderId=Job.JobOrderID
INNER JOIN Customer
ON Customer.CustId=Orders.OrderCustId
INNER JOIN Employee
ON Employee.EmpId=Job.JobEmpID

OK, I figured it out and I'm posting it here for any future reference.
SELECT o.OrderID, j.JobStatus, o.OrderStatus, c.CustID, c.CustName, c.CustContact, c.CustDue, e.EmpID, e.EmpName, e.EmpContact, o.Oredrvalue
FROM Orders o
LEFT JOIN Customer c
ON o.OrderCustID=c.CustID
LEFT JOIN Job j
ON o.OrderID=j.JobOrderID
LEFT JOIN Employee e
ON j.JobEmpID=e.EmpID
I performed left join on all occasions because I need all the records from Orders table. Thanks a lot to all who responded.

Related

Lookup table with columns in the same joined table

In a Microsoft SQL Server Database I have a lookup table that has the following structure:
Assistants:
EmployeeId, AssistantId
Those two IDs are in a second table:
Employees:
Id, FirstName, LastName
I would like to join the two tables and list each Employee and there assistants, it could be more than one. I have tried the following which I thought would work:
select * from Assistants
join Employees
on Assistants.EmployeeId = Employees.Id AND Assistants.AssistantId = Employees.Id
However it returns nothing, any ideas how I can achieve a listing of each employee and there assistants?
You have to use the employee table twice - once to get the employee and once to get the assistant.
I'm assuming not all employees have assistants, so you should probably use left joins:
SELECT * -- You really should specify the columns names here
FROM Employees As Emp
LEFT JOIN Assistants
ON Emp.Id = Assistants.EmployeeId
LEFT JOIN Employees As Assist -- You should probably find a better name for this alias...
ON Assistants.AssistantId = Assist.Id
That will give you a list of all employees and their assistants.
If, however, you can have multiple level of assistants (i.e. the CTO have an assistant CTO and they have an assistant themselves), you will need a recursive cte.
Off the top of my head. Something like this.
Select E.ID, E.FirstName, E.LastName, TBLA.FirstName, TBLA.LastName
FROM Employees E
LEFT JOIN (
Select E.FirstName, E.LastName, A.AssistantId
from Assistants A
INNER JOIN Employees on A.AssistantId = Employees.ID
) TBLA ON TBLA.AssistantId = E.ID
where TBLA.AssistantId is NOT null

Insert Into TABLE from 3 separate tables

I am getting my face kicked in....
I have a total of 4 tables
1. Business (BusinessID, CustomerID, BusName, Territory)
2. Customer (CustomerID, Name)
3. Sales (BusinessID, CustomerID, Territory, Jan, Feb, Mar, Apr, May, Jun)
4. Performance (this is the table I want the info in)
I've already created the table to have the following columns, BusinessID, CustomerID, BusName, Name, Territory, Jan,Feb,Mar,Apr,May,Jun
Every time I try to insert its not properly joining and I am getting a bunch of errors "multi-part identifier could not be bound"
insert into Performance (BusinessID, CustomerID, BusName, Name, Territory, January2018, February2018, March2018, April2018, May2018, June2018)
select Business.BusinessID, Customer.CustomerID, Business.BusName, Customer.Name, Sales.Territory, Sales.January2018, Sales.February2018, Sales.March2018, Sales.April2018, Sales.May2018, Sales.June2018
from Business A
inner join Customer B ON a.CustomerID = b.CustomerID
inner join Sales C ON b.CustomerID = c.CustomerID;
Due to this error I had to do 3 seperate insert into and that caused a bunch of nulls....
face palm is happening and could use some advice.
Image: enter image description here
Thanks,
VeryNew2SQL
You have used table ALIASES, so you have to use those aliases in you SELECT
A for Business, B for Customer and C for Sales.
Read about ALIASES here.
select A.BusinessID, B.CustomerID, A.BusName, B.Name, C.Territory, C.January2018, C.February2018, C.March2018, C.April2018, C.May2018, C.June2018
from Business A
inner join Customer B ON a.CustomerID = b.CustomerID
inner join Sales C ON b.CustomerID = c.CustomerID;
When you create a table alias in your FROM and JOIN clauses, you need to refer to the aliases in your SELECT statement and not the actual table names.
Alternatively, leave your SELECT statement as it is, and adjust your table names to remove the alias. You'll then need the join conditions to refer to your actual table names, rather than the alias. So for example;
select Business.BusinessID, Customer.CustomerID, Business.BusName, Customer.Name, Sales.Territory, Sales.January2018, Sales.February2018, Sales.March2018, Sales.April2018, Sales.May2018, Sales.June2018
from Business
inner join Customer ON Business.CustomerID = Customer.CustomerID
inner join Sales ON Customer.CustomerID = Sales.CustomerID;
Even just try running the SELECT statement above first to make sure you get the query correct before trying it in your insert.

Northwind query and modification

I would like to make such modification to Northwind database
Add Chocolade to all orders made by customer ALFKI, not
including it yet
(I tried to used insert into, by unfortunately I failed.)
I've taken database schema from here (https://northwinddatabase.codeplex.com/). So, logic is simple: find all orders from customer 'ALFKI', find chocolate productID and add all this information to table Orders_Details.
INSERT INTO Order_Details(orderID, productID, UniPrice, Quantity, Discount)
SELECT O.orderID,
pr.productID,
<your price>,
<your quantity>,
<your discount>
FROM Orders AS O,
(SELECT TOP 1 productID FROM Products WHERE productName like '%Chocolate%') AS pr
JOIN Customers AS C ON O.customerID = C.customerID
WHERE C.companyName = 'ALFKI'

How do I build a query that crosses multiple tables?

Here are my tables:
CUSTOMER
Cust_ID (PK)
Name
ORDERS
Order_ID (PK)
Cust_ID (FK)
ORDER_LINE
Order_ID (pk)
Part_ID (FK)
PART
Part_ID (PK)
Part_Description
Now I want to list the customer details, the part number and the description of the parts that each customer ordered.
How do i do this?
Thanks.
You should use "JOIN" using the FK, but from what I see you don't have a foreign key between "ORDERS" and "ORDER_LINE". Are you sure you're not missing something from the table definition, ie: ORDER_LINE should maybe have the ORDER_ID as a FK ?
Hope this helps
You can try something like
SELECT c.*,
p.*
FROM CUSTOMER c INNER JOIN
ORDERS o ON c.Cust_ID = o.Cust_ID INNER JOIN
ORDER_LINE ol ON o.Order_ID = ol.Order_Number INNER JOIN
PART p ON ol.Part_Number = p.Part_Number
Have a look at
Join (SQL)
An SQL join clause combines records from two or more tables in a
database.
SQL Joins
The JOIN keyword is used in an SQL statement to query data from two or
more tables, based on a relationship between certain columns in these
tables.
And for some graphic examples
JOIN Basics
What you need is a simple straightforward JOIN like so:
SELECT
c.Cust_ID,
c.Name,
l.Part_Number,
l.Part_Description
FROM CUSTOMER c
INNER JOIN ORDERS o ON c.Cust_ID = o.Cust_ID
INNER JOIN ORDER_LINE ol ON o.OrdeR_ID = ol.Order_Number
INNER JOIN PART l ON ol.Part_Number = l.Part_Number
You want an SQL "join", such as:
SELECT c.Name, ol.Part_Number, p.Part_Description
FROM Customer AS c
JOIN Orders AS o ON c.Cust_ID = o.Cust_ID
JOIN Order_Line AS ol ON o.Order_ID = ol.Order_Number
JOIN Part AS p ON ol.Part_Number = p.Part_Number
Be aware that without a WHERE clause, this query will return all all parts in all orders for all customers, which will really hammer the network and perform poorly on anything but a tiny database:
WHERE (c.Cust_ID = MyCustomerID)
MySQL join syntax
SQL Server join syntax

Need help creating a query for a non-normalized database

I've never worked with a non-normalized database before, so I'll try and explain my problem as best I can. So I have two tables:
The customers table holds all the customers information, and the orders table holds all the orders that they have placed. I haven't listed all the fields in the tables, just the ones that I need. The customer number in both tables is not the primary key, but I'm inner joining on them anyway. So the problem I'm having is that I don't know how to make a query that:
Selects all the customers with their first name, last name, and email, and also show the most recent orderdate, most recent total, and most recent ordertype. I know that I have to use a max() aggregate for the date, but that's as far as I got. Please help a noob out.
You can try:
SELECT FirstName,
LastName,
Email,
OrderDate,
OrderTotal,
OrderType
FROM Customers AS C
INNER JOIN Order AS O
ON O.CustomerNumber = C.CustomerNumber AND
O.OrderDate = (
SELECT MAX (O1.OrderDate)
FROM Order AS O1
WHERE O1.CustomerNumber = C.CustomerNumber)
)
assuming that Orders.OrderDate is unique for each CustomerNumber, does this work for you? if a single CustomerNumber has more than one entry in Order for OrderDate, you'll get each of those rows.
select c.FirstName, c.LastName, c.Email, o.OrderDate, o.OrderTotal, o.OrderType
from Customers c
join
(select CusomterNumber, max(OrderDate) as MostRecentOrderDate
from Orders
group by CustomerNumber
) mro on mro.CustomerNumber=s.CustomerNumber
join Orders o on o.OrderDate=mro.MostRecentOrdeDate and
o.CustomerNumber=mro.CustomerNumber
Try this:
SELECT
Customers.*, Orders.*
FROM
Customers
JOIN
(SELECT
Customer_Number,
MAX(Order_Date) OrderDate
FROM
Orders
GROUP BY
Customer_Number
) as Ord ON Customers.Customer_Number = Ord.Customer_Number
JOIN Order ON Orders.Customer_Number = Ord.Customer_Number
If you are doing this with SQL Server use the query designer and basically all you want to do is do a join since you have two keys that are the same one in Customer Table ->Customer Join on Order->Customer alias the Customer table as C and Orders table as O
so for example
SELECT Customer.*, Orders.*
From Customer c, Orders O INNER JOIN O where C.Customer Number = O.Customer Number
This should be enough to get you started.. if you don't want all the fields then fully qualify the names for example
SELECT C.FirstName, C.LastName, O.OrderDate, O.OrderType FROM Customer C, Orders O
WHERE C.Customer NUmber = O.Customer Number //this is another way of doing a Join when working with the where Clause.

Resources