Getting the quantity of currently available items - sql

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

Related

Adventureworks sqlzoo

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 ;)

Access: Find partial duplicates, show only one and sum a value

I have a database for my invoices. I would like to make a form where I list all purchases from one customer. If the customer bought the same item more than once I'd like to show that item only once and sum the quantity field. I'd like to find an SQL solution, but I'm a bit stuck.
This is the query in my form:
SELECT Order.fkCustID, Order.OrderID, OrderLine.fkProductID, OrderLine.Qty, ProductList.Item
FROM ProductList INNER JOIN
([Order] INNER JOIN
OrderLine
ON Order.OrderID = OrderLine.fkOrderID
) ON ProductList.ProductID = OrderLine.fkProductID
ORDER BY ProductList.Item;
The OrderLine table contains the individual products bought, the Order table links these to my customer table. ProductList contains the product description.
So where fkCustID and fkProductID are the same, I'd like to only show the oldest entry and sum the Qty field of both.
I think you just want an aggregation query, that looks something like this:
SELECT ol.fkProductID, SUM(ol.Qty) as qty, pl.Item
FROM ProductList as pl INNER JOIN
([Order] as o INNER JOIN
OrderLine as ol
ON o.OrderID = ol.fkOrderID
)
ON pl.ProductID = ol.fkProductID
WHERE o.fkCustID = ???
GROUP BY ol.fkProductID, pl.Item
ORDER BY pl.Item;

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.

Is a join necessary in this sql query?

Suppose I have a table Orders in sql with 4 columns (OrderId int, ProductID int, Price money, Size int) with OrderID and ProductID as a joint primary key.
If I want a query to return the most recent order (along with price and size) for every product (i.e., maximal OrderId) is there a way to do this without a join?
I was thinking of the following:
select o.OrderId, o.ProductId, o.Price, o.Size
from Orders o inner join
(select Max(OrderId) OrderId, ProductId from Orders group by ProductId) recent
on o.OrderId = recent.OrderId and o.ProductId = recent.ProductId
but this doesn't seem like the most elegant solution possible.
Also, assume that an order with multiple products generates multiple rows. They are both necessarily part of the primary key.
No, there isn't. You've got the right idea. You need to do the subquery to get the max(orderID), productID pair, and then join that to the full table to limit the query to the rows in the full table that contain the max OrderId.
select
MAX(o.OrderId) as NewestOrderID,
o.ProductId,
o.Price,
o.Size
from Orders o
Group by
o.ProductId,
o.Price,
o.Size