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'
Related
So this is what I am working with new to sql and still learning been stuck on this for a few days now. Any advice would be appreciated I attached the image of the goal I'm trying to achieve
OrderItem And Product Table
Order And OrderItem Table(https://i.stack.imgur.com/pdbMT.png)
Scenario: Our boss would like to see the OrderNumber, OrderDate, Product Name, UnitPrice and Quantity for products that have TotalAmounts larger than the average
Create a query with a subquery in the WHERE clause. OrderNumber, OrderDate and TotalAmount come from the Order table. ProductName comes from the Product table. UnitPrice and Quantity come from the OrderItem table.
This is the code I came up with but it causes product name to run endlessly and displays wrong info.
USE TestCorp;
SELECT DISTINCT OrderNumber,
OrderDate,
ProductName,
i.UnitPrice,
Quantity,
TotalAmount
FROM [Order], Product
JOIN OrderItem i ON Product.UnitPrice = i.UnitPrice
WHERE TotalAmount < ( SELECT AVG(TotalAmount)
FROM [Order]
)
ORDER BY TotalAmount DESC;
Best guess assuming joins and fields not provided.
SELECT O.OrderNumber, O.orderDate, P.ProductName, OI.UnitPrice, OI.Quantity, O.TotalAmount
FROM [Order] O
INNER JOIN OrderItem OI
on O.ID = OI.orderID
INNER JOIN Product P
on P.ID= OI.ProductID
CROSS JOIN (SELECT avg(TotalAmount) AvgTotalAmount FROM [Order]) z
WHERE O.TotalAmount > z.AvgTotalAmount
Notes:
You're mixing join notations don't use , and inner join together that's mixing something called ANSI Standards.
I'm not sure why you have a cross join to product to begin with
You don't specify how to join Order to order item.
It seems very odd to be joining on Price.... join on order ID or productID maybe?
you could cross join to an "Average" result so it's available on every record. (I aliased this inline view "Z" in my attempt)
so what the above does is include all Orders. and for each order, an order item must be associated for it to be included. And then for each order item, a productid must be included and related to a record in product. If for some reason an order item record doens't have a related entry in product table, it gets excluded.
I use a cross join to get the average as it's executed 1 time and applied/joined to every record.
If we use the query in the where clause it's executed one time for EVERY record (unless the DB Engine optimizer figures it out and generates a better plan)
I Assume
Order.ID relates to OrderItem.OrderID
OrderItem.productID relates to Product.ID
Order.TotalAmount is what we are wanting to "Average" and compare against
Every Order has an Order Item entry
Every Order Item entry has a related product.
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.
I have two tables in SQL server. first one is table of customers info and second includes all purchases,
At first Table i have id of our customers, and the purchases table although has the id of who bought that product. so how can i select all customers table that include how many time they purchased products?
i tried this
SELECT TOP 2000 COUNT(tblpurchase.id) as id2,tblcustomers.* From tblpurchase
right join on tblpurchase.id=tblcustomers.id
but didn't word. how can i solve this?
Use OUTER APPLY
SELECT TOP 2000 tblcustomers.* ,M.CustomerCount
From tblcustomers
OUTER APPLY(
SELECT COUNT(*) as CustomerCount
from tblpurchase
WHERE tblpurchase.CustomerIDColumn = tblcustomers.id
)M
Here tblpurchase.CustomerIDColumn use actual name of customerID column
Also you can with LEFT JOIN
SELECT TOP 2000
C.*,
P.CustomerCount
From
tblcustomers C LEFT JOIN
(
SELECT
TP.CustomerId,
COUNT(*) as CustomerCount
FROM
tblpurchase TP
GROUP BY
TP.CustomerId
) P ON C.Id = P.CustomerId
I have an Orders table and an OrderItem table. I would like to select all OrderItems that have been shipped between 2 dates, and select the additional OrderItem of a certain type that was shipped outside of the 2 dates if it's part of an Order that has OrderItems shipped between the 2 dates.
This seemed really easy when I first thought of it, but I'm having a hard time putting it into a SQL statement. I'm using SQL Server.
EDIT:
Yes, I am familiar with the between keyword. What I have is an Order, Say Order #10001. It has 2 items, a product that is shipped on 01/20/2015 and a warranty that is marked as shipped on 02/04/2015. So when I run my query:
SELECT *
FROM OrderItems
WHERE ShipDate BETWEEN '01/01/2015' AND '01/31/2015'
I only get the 1 product, I want to get the warranty that is on the Order as well.
Hope that clarifies my question.
You can do this like this:
SELECT *
FROM OrderItems
WHERE OrderID IN(
SELECT DISTINCT OrderID
FROM OrderItems
WHERE ShipDate BETWEEN '01/01/2015' AND '01/31/2015'
)
Or:
SELECT *
FROM OrderItems oi1
JOIN (
SELECT DISTINCT OrderID
FROM OrderItems
WHERE ShipDate BETWEEN '01/01/2015' AND '01/31/2015'
) oi2 ON oi1.OrderID = oi2.OrderID
Are you familiar with BETWEEN keyword?
SELECT ...
WHERE col BETWEEN AND
If you add more information, such as sample data to your question, I can elaborate on the answer.
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.