Adventureworks sqlzoo - sql

A "Single Item Order" is a customer order where only one item is ordered. Show the SalesOrderID and the UnitPrice for every Single Item Order
Hi,
I tried this question and this is my answer below:
SELECT s.salesOrderID, s.UnitPrice
FROM SalesOrderDetail s
INNER JOIN Product p ON s.ProductID = p.ProductID
GROUP BY s.salesOrderID, s.unitPrice
HAVING count(s.OrderQty) = 1
.please let me know if this is current or else provide a solution .Looking for answers
Thank you

I would suggest:
SELECT MAX(s.salesOrderID) as salesOrderId, MAX(s.UnitPrice) as UnitPrice
FROM SalesOrderDetail s
GROUP BY s.OrderID
HAVING COUNT(*) = 1;
Based on your query, UnitPrice is in SalesOrderDetail not Product, so the JOIN is not necessary. If UnitPrice is really in Product, then you need the JOIN.
Note the logic of the query. You want to count the number order detail records per order. So, that should be the aggregation. The HAVING clause ensures that there is just one detail record for the order.
Hence, the MAX() function return the values on that single row.

I took the question to mean a customer order of exactly one type of item with a order quantity of 1. The JOIN is unecessary as all the needed data is in one table. Here was my solution:
SELECT SalesOrderID, UnitPrice
FROM SalesOrderDetail
WHERE SalesOrderID IN
(SELECT SalesOrderID
FROM SalesOrderDetail
GROUP BY SalesOrderID HAVING COUNT(ProductID) = 1) AND OrderQty = 1
This eliminates orders that have more than one item of a single quantity.
SQLZoo doesn't have smiley faces for these answers, so I'm not sure if I'm correct ;)

Related

SQL query that may be a subquery question or an inner join

I have a homework assignment that asks:
"For each customer whose total sales amount is greater than $250, list customer ID, customer name, and total sales amount of the customer. Give descriptive names for all computed fields."
Normally, I would never come to S.O. for homework answers, as I would just push through and figure it out, but this one seems to have me stuck.
This is my incorrect query to the question:
SELECT customerid
FROM customer
WHERE customerid In (SELECT sum(untipricesold) AS totalSales
FROM orderline WHERE sum(orderline.unitpricesold) > 250)
GROUP by customerid;
The result I got is:
"group function is not allowed here".
I have attached a screenshot of the relevant tables that SHOULD be used for this question. Again, this isn't something I would usually do and am completely against cheating for school, but please help.
You need HAVING clause when you are come with filtration after aggregation or groping :
So, i would inclined with JOIN :
SELECT c.customerid , c.customername, o.TotalSales
FROM customer c INNER JOIN
(SELECT customerid, SUM(untipricesold) AS TotalSales
FROM orderline O
GROUP by customerid
HAVING SUM(untipricesold) > 250
) o
ON o.customerid = c.customerid;
You need a HAVING clause. Also, you probably want to be selecting the customerid in the subquery, rather than the sum, since you are comparing to customerid in the outer query.
SELECT customerid
FROM customer
WHERE customerid IN (SELECT customerid FROM orderline
GROUP by customerid HAVING SUM(untipricesold) > 250);

SQL a SELECT within a SELECT? Northwind (Microsoft)

First of all, I'm practicing with Northwind database (Microsoft creation).
The table design I'm working with is:
The question I'm trying to solve is:
Which Product is the most popular? (number of items)
Well, my query was:
SELECT DISTINCT
P.ProductName
FROM
Products P,
[Order Details] OD,
Orders O,
Customers C
WHERE
C.CustomerID = O.CustomerID
and O.OrderID = OD.OrderID
and OD.ProductID = P.ProductID
and P.UnitsInStock = (SELECT MAX(P.UnitsInStock) Items
FROM Products P)
Now, I had exactly one result as they asked:
ProductName
1 Rhönbräu Klosterbier
Yet, I doublt that my query was good. Do I really need a SELECT within a SELECT?
It feels like duplication for some reason.
Any help would be appreciated. Thanks.
To get the most popular product (bestselling product) use query
SELECT ProductName, MAX(SumQuantity)
FROM (
SELECT P.ProductName ProductName,
SUM(OD.Quantity) SumQuantity
FROM [Order Details] OD
LEFT JOIN Product P ON
P.ProductId = OD.ProductID
GROUP BY OD.ProductID
) Res;
Does the most units in stock necessarily equate to the most popular product? I don't think that is always a true statement (It could even be the opposite in fact.).
To me the question is asking, which is the most popular product sold. If you think about it that way, you'd be looking at the amount sold for each product and selecting the product with the most sold.
Does that make sense?
With regards to your specific query, the query only utilizes the Products table. You make joins, but they are not used at all in the query and should get overlooked by the query optimizer.
I would personally rewrite your query as the following:
SELECT
P.ProductName
FROM
Products P
INNER JOIN
(SELECT
MAX(P.UnitsInStock) AS Items
FROM Products P) maxProd
ON P.UnitsInStock= maxProd.Items
About your question, it is perfectly acceptable to utilize a subquery (the select in the where clause). It is even necessary at times. Most of the time I would use an Inner Join like I did above, but if the dataset is small enough, it shouldn't make much difference with query time.
In this scenario, you should rethink the question that is being asked and think about what being the most popular item means.
Rethinking the problem:
Let's look at the datasets that you've shown above. Which could be used to tell you how many products have been sold? A customer would have to order a product, right? Looking at the two tables that are potentially applicable, one contains details about number of items sold, quantity, or you could think of popularity in terms of the number of times appearing in orders. Start with that dataset and use a similar methodology to what you've done, but perhaps you'll have to use a sum and group by. Why? Perhaps more than one customer bought the item.
The problem with the dataset is it doesn't tell you the name of the product. It only gives you the ID. There is a table though that has this information. Namely, the Products table. You'll notice that both tables have the Product ID variable, and you are able to join on this.
You can find the most popular product by counting the number of orders placed on each product .And the one with most number of order will be the most popular product.
Below script will give you the most popular product based on the the number of orders placed .
;WITH cte_1
AS(
SELECT p.ProductID,ProductName, count(OrderID) CNT
FROM Products p
JOIN [Order Details] od ON p.ProductID=od.ProductID
GROUP BY p.ProductID,ProductName)
SELECT top 1 ProductName
FROM cte_1
ORDER BY CNT desc
if you are using SQL server 2012 or any higher version, use 'with ties' for fetching multiple products having same order count.
;WITH cte_1
AS(
SELECT p.ProductID,ProductName, count(OrderID) CNT
FROM Products p
JOIN [Order Details] od ON p.ProductID=od.ProductID
GROUP BY p.ProductID,ProductName)
SELECT top 1 with ties ProductName
FROM cte_1
ORDER BY CNT desc
In your sample code,you tried to pull the product with maximum stock held. since you joined with other tables (like order details etc) you are getting multiple results for the same product. if you wanted to get a product with maximum stock,you can use any of the following script.
SELECT ProductName
FROM Products P
WHERE P.UnitsInStock = (SELECT MAX(P.UnitsInStock) Items
FROM Products P)
OR
SELECT top 1 ProductName
FROM Products P
ORDER BY P.UnitsInStock desc
OR
SELECT top 1 with ties ProductName --use with ties in order to pull top products having same UnitsInStock
FROM Products P
ORDER BY P.UnitsInStock desc

SQL based Northwind, hard time on filtering

So in a practice site there is a question:
Which Product is the most popular? (number of items)
This means that There are Customers, and they want to know the most popular Ordered Product by the Customers(Overall Orders of TOP 1 ordered Product).
I Sincerely do not know How to solve this one.
Any help?
What I've tried so far is:
SELECT TOP(1) ProductID, ProductName
FROM Products
GROUP BY ProductID, ProductName
ORDER BY COUNT(*) DESC
But that's far from what they have asked.
In this one, I just get the top 1 Product with the lowest count, but that doesn't mean anything about the customers who ordered this product.
That only means that this specific Item could have been at low quantity and still is lower then the others, while the others were very high quantity and now just low (but still not low enough)
I hope I was clear enough.
If the data exists in that table, you might just need to order by something more sophisticated than count, like summing the quantity (if that column exists). Also, if ProductID and ProductName are already unique identifiers, note that you don't need the group by and sum at all.
SELECT TOP(1) ProductID, ProductName
FROM Products
GROUP BY ProductID, ProductName
ORDER BY SUM(Quantity) DESC
I don't know what your keys are, but it sounds like you actually want to be counting how many times it was ordered by customers, so you may need to join on the Customers table. I am assuming here that you have a table Orders, that has one line per order and shares the ProductID key. I also assume that ProductID is unique in Products (which may not be true based on your first query).
SELECT TOP(1) Products.ProductID, Products.ProductName
FROM Products
LEFT JOIN Orders
ON Orders.ProductID = Products.ProductID
GROUP BY Products.ProductID, Products.ProductName
ORDER BY COUNT(Orders.OrderID) DESC
This really depends on what tables and keys you have available to you.
Select top 1 P.ProductID,P.ProductName,Sum(OD.Quantity)AS Quantity
From [Order Details] OD
inner join Products P ON P.ProductID = OD.ProductID
Group By P.ProductID,P.ProductName
Order by Quantity Desc
You can workout something like this, (Table name/schema may differ)
with cte_product
as
(
select ProductID,Rank() over (order by Count(1) desc) as Rank from
Orders O
inner join Product P
on P.ProductID = O.ProductID
group by ProductID
)
select P.productID, P.ProductName from
cte_product ct
inner join product p
on ct.productId = p.ProductID
where ct.Rank = 1
Crux is usage of RANK() to get most popular product. Rest you may fetch columns as per need using relevant Joins.

Getting the quantity of currently available items

I am writing a simple application in java and I am stuck in one sql statement. Lets say that I have two tables called items with attributes itemId and quantity and orderDetails also with attributes itemId and quantity. In the table Items I keep all the items and in orderDetails table I keep an itemId and quantity which was hired out to the customers. The goal is to write a sql statement which returns table with itemId and quantity of items which are currently available. I tried it several ways but I did not find a proper solution. (I am very very new in sql). This is one of them which I tried:
SELECT itemId, quantity - (SELECT SUM(quantity) FROM orderdetails GROUP BY itemId)
FROM items, orderdetails
WHERE orderdetails.itemid = items.itemid;
Thanks in advance!
I think that you could use correlated query (which IIRC should generally be avoided):
select
items.itemid,
items.quantity -
(select sum(quantity)
from orderdetails
where orderdetails.itemid = items.itemid group by itemid) left
from items;
Or you could join two tables:
select items.itemid, quantity - total.q left from
items,
(select itemid, sum(quantity) q from
orderdetails
group by itemid) total
where items.itemid = total.itemid (+);
You must provide some table data, for example:
select items.itemId, items.quantity - sum(quantity)
from items, orderdetails
where orderdetails.itemid = items.itemid
group by items.itemId, items.quantity

SQL query for showing the products which sell better, based on how many times an index is found in the table?

I have customer table which have products and quantity , I need to retrieve those products which sell better in the company.
How would I accomplish this with an SQL query?
Out of the common-assumption of a product/order/sales table schema, the following query is constructed. So please either show us your tables or change the query according to your tables.
This will give you the best product:
SELECT s.ProductID, ProductName, Max(s.Quantity) as MaxSales
FROM Products p, SalesOrder s
WHERE p.ProductID = s.ProductID
GROUP BY s.ProductID;
This will give you 10 best products:
SELECT TOP 10 s.ProductID, ProductName, s.Quantity
FROM Products p, SalesOrder s
WHERE p.ProductID = s.ProductID
ORDER BY s.Quantity DESC;
I think a simple order by clause should do
select products, quantity
from tableName
order by quantity desc
If you need only top 5 for example, add "Top 5" between select and products word in above query
Hope that helps