Counting records in a table given corresponding ID - sql

This seems like such an easy query to run yet I cannot get it to work and I'm starting to rethink why I chose to tackle this project.
I am trying to find how many records are in a table where an id is identical. For example
select productid, productgroup, shelflvl, shelfaisle, Count(Shelfaisle) AS totalaisles
from productlocation
Where productid= productid AND productgroup = 'canned'
Group By productid, productgroup, shelflvl, shelfaisle
A product with the same id can be in a different aisle and on a different shelflvl. All I am trying to do is see how many aisles a product is in and I cannot for the life of me get it to work properly.
Any help is appreciated thank you!

I'm assuming a product cannot belong to many productgroups.
Remove Shelfaisle from GROUP BY as this is what you're trying to count.
Also, a COUNT(DISTINCT Shelfaisle) would prevent duplicates (if applicable).
Lastly, you don't need a productid=productid condition which apparently always yields true.
Cut a long story short:
select
productid, productgroup, shelflvl, Count(distinct Shelfaisle) AS totalaisles
from productlocation
Where productgroup = 'canned'
Group By productid, productgroup, shelflvl

Don't group by the column you are trying to aggregate:
select productid, productgroup, Count(Shelfaisle) AS totalaisles
from productlocation
Where productid=productid AND productgroup = 'canned'
Group By productid, productgroup

How about:
select productid, productgroup, Count(shelfaisle) AS totalaisles
from productlocation
Where productid= productid AND productgroup = 'canned'
Group By productid,productgroup
You are adding in additional columns to group by, which means that you can't isolate the product as the thing to count. You are counting products on specific rows on specific shelflevels, when you only need the product and shelfaisle.

This would work:
SELECT productid, shelflvl, MIN(productgroup) AS productgroup,
COUNT(Shelfaisle) AS totalaisles
FROM productlocation
WHERE productgroup = 'canned'
GROUP BY productid, shelflvl
ORDER BY productid;

Related

SQL query MAX() function

select ProductID,ProductName,QuantityPerUnit
from Products
where Products.UnitPrice=Max(UnitPrice)
What is wrong in this query?
I had tried 'having' in place of 'where' tag.
select ProductID,ProductName,QuantityPerUnit
from Products
having Products.UnitPrice=Max(UnitPrice)
it must produce result with max unit price,
ProductID ProductName QuantityPerUnit
38 Côte de Blaye 12 - 75 cl bottles
If you want the product(s) with the maximum UnitPrice:
select ProductID,ProductName,QuantityPerUnit
from Products
where UnitPrice = (select Max(UnitPrice) from Products)
This query:
select Max(UnitPrice) from Products
returns the maximum UnitPrice.
If there are more than 1 products with that price, they will all be returned.
If you want just 1, you can use LIMIT 1 or TOP 1, depending on the rdbms you use.
You cannot simply use aggregate function in a where clause unless it's in a subquery.
Try :::
select ProductID,ProductName,QuantityPerUnit from Products
Where Products.UnitPrice= (select Max(UnitPrice) from Products)
If you're using TSQL, then better use
select top 1 With ties ProductID,ProductName,QuantityPerUnit from Products
Order by UnitPrice desc
This will give you all the products with highest unit price and is efficient since there's no subquery.
Use sub query to find max price
SELECT ProductID, ProductName, QuantityPerUnit
FROM Products
WHERE UnitPrice = (SELECT Max(UnitPrice) FROM Products)
can use HAVING clause
SELECT ProductID, ProductName, QuantityPerUnit FROM Products
GROUP BY ProductID, ProductName, QuantityPerUnit
HAVING UnitPrice = MAX(UnitPrice)
What is wrong with your query is that you are mixing aggregation value with raw values in the query.
If you want only one row, I would recommend a different approach:
select ProductID, ProductName, QuantityPerUnit
from Products
order by UnitPrice desc
fetch first 1 row only;
Although fetch first is standard SQL, not all databases support it, so you may need the appropriate syntax for your database.
What I tried is:
Select Max(UnitPrice) From Products
select Max(UnitPrice) ProductID,ProductName,QuantityPerUnit
from Products
Group By ProductID,ProductName,QuantityPerUnit having Max(UnitPrice)>200

Sorting results of aggregate function

This code:
SELECT ProductID, COUNT(ProductID) AS Occurrences
FROM OrderDetails
Group By ProductID;
is my attempt to take the productIDs that occur in an orderDetails table, count how many orders contain that product, and then sort the productID counts descending. In layman's terms, I want to show which products are the most popular, by showing their count in descending order so that the products that "sold" the most will occur at the top. The issue I have is that when I tried to use "Group by" with "Occurrences", it spat out an error that I cannot use aggregate functions with group by. If I group by ProductID, it shows the counts all over the place, which isn't the most useful way to present the information.
This should work:
SELECT ProductID, COUNT(ProductID) AS Occurrences
FROM OrderDetails
Group By ProductID
Order By COUNT(ProductID) DESC;
What you really want to use if you want to know the popularity of the products is SUM not COUNT:
SELECT ProductID,
sum(Qty) AS Occurrences
FROM OrderDetails
Group By ProductID
Order By sum(Qty) DESC;
COUNT will give you interesting results. Or you could use count of orders like this:
select ProductID
count(distinct OrderNumber) as NumberOfOrders
from OrderDetails
group by ProductID
order by count(distinct OrderNumber) desc;

List orderId, Number of Order Items, and Total Order Price - not a GROUP BY expression

I know the "not a GROUP BY expression" has been asked, but mine seems to be very different.
I'm trying to get a list of data from a view but I am getting the "not a GROUP BY expression" error.
Code:
Select orderid, count(orderid) as Number_Of_Order_Items , count(orderid) * orderprice as Total_Order_Price
from orderdetail
Group by orderid
order by orderid
Basically I am expecting to get the orderID, how many times that order ID appears and then multiply the number of times the orderID exists by the OrderPrice.
I have all of the non-aggregate clauses in my Group By, so what is happening here?
Just use sum() on the price:
Select orderid, count(orderid) as Number_Of_Order_Items,
sum(orderprice) as Total_Order_Price
from orderdetail
Group by orderid
order by orderid;
Note: This assume that orderprice is really a separate price on each detail record that needs to be summed up. In some cases, there might be a quantity column as well -- but then I would expect the column to be called something like productprice or unitprice.

SQL Using sum command with "in" clause

I have sql tables listed as picture below.
And my Query is :
Select * from tblOrderDetails where OrderID in
(Select OrderID from tblOrders where CustomerID = 523456)
Which returns values from tblOrderDetails like
Query brings all sale details for selected customer as expceted. But I want to use SUM on rows which has same ProductID. Expected output should look like this :
Rows with same productID, quantity and price gets summed and also rows are merged. But it must be done within selected CustomerID.
I've tried SUM command with many different ways but can't get it to work. Please suggest. Thanks.
It sounds like you don't know about the GROUP BY clause.
Perhaps this is what you are trying to do?
Select CustomerID,ProductId,SUM(Quantity) Quantity,SUM(TotalPrice) TotalPrice from tblOrderDetails where OrderID in (Select OrderID from tblOrders where CustomerID = 523456)
GROUP BY CustomerID,ProductId
This groups everything by same customer then by same products, allowing the SUMs only on those merged subsets
You'll be wanting to use SUM and GROUP BY to attain the results you're looking for.
SELECT ProductID, SUM(Quantity) AS Quantity, SUM(TotalPrice) AS TotalPrice
FROM tblOrderDetails
WHERE OrderID IN
(
SELECT OrderID
FROM tblOrders
WHERE CustomerID = 523456
)
GROUP BY ProductID

How to get the products that all Warehouse exist?

I have a question as the title,I wanna get the products which appeared in every Warehouse,
I have no idea when i thought long time,i found i am so beetleheaded,
Thare are three tables in my sql server database:
Product
(
productID,
name,model,
size,
color
)
Warehouse
(
warehouseID,
name,
address
)
Inventory
(
warehouseID,
productID,
quantity
)
i hope someone help me to have a look and can write the sql that get the result
Thank you.
Use a GROUP BY to count the number of warehouses each product is in. Accept those rows for which this count is equal to the total number of warehouses.
SELECT productID
FROM Inventory
WHERE quantity > 0
GROUP BY productID
HAVING COUNT(*) = (SELECT COUNT(*) FROM Warehouse)
This assumes that (productID, warehouseID) is unique in the inventory table. If it is not then use COUNT(DISTINCT warehouseID) instead of COUNT(*).