SQL Loop Distinct Values for Use in Calculated Columns - sql

I am trying to do something in SQL here. I have a product type, lets call it "Food" and I have a table with names of stores, product types, and product names, let's call the stores, "Red, Blue, Green". I want to run a query that finds every store in which Product Type "Food" was sold.
So something like this:
SELECT DISTINCT [Stores]
FROM dbo.SalesTable
WHERE [Product Type] = 'Food'
Then I want to use each distinct store name in a loop, to populate calculated columns telling me the sales numbers of each product type in the individual stores. The actual Product Type could be many things and each would have a unique list of stores. So I will probably declare the VARCHAR variable for use in the query.
Basically I think column A would be product Names for the product type used, and columns 2 through X would be the sales of each product at each store. If there were 5 stores then those calculations would sit in columns 2 through 6.
I just have no experience using loops in SQL and hopefully somebody can help out. Thanks so much!!

Grouping is going to be your key here.
SELECT [Product Type], Stores, SUM(SalesTable.column1), COUNT(SalesTable.column2) ...
FROM SalesTable
GROUP BY [Product Type], Stores

Related

Aggregate my quantity sum in a way that doesn't lead to the storeID repeating?

I am writing a SQL query that needs to show the total number of orders from each store. The issue I am running into, is that while I can figure out how to sum the orders by product and each product is only sold by one store, I can't figure out how to total the orders by store alone
This is the code I currently have
SELECT storeID AS [STORE], Product_ID
, SUM(quantity) AS [ORDERS BY STORE]
FROM Fulfillment, Store
GROUP BY storeID, Product_ID;
This line of code leads to a repeat of storeID in the results, where ideally, I would only want storeID to be included in the results once with the total quantity of all of Product_ID being included. I tried to remove Product_ID from the GROUP BY statement, but this resulted in the following error
Column 'Fulfillment.Product_ID' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
I'm new to SQL and am trying to learn, so any help and advice is greatly appreciated
#ZLK is correct that if your goal is a total number of units ordered ("quantity") of any product, simply remove the [product_id] column from the SELECT and GROUP BY.
However, it appears that you're referencing two tables ("FROM Fulfillment, Store") and not specifying how those tables are joined, creating a cartesian join - all rows in one table will be joined to all rows in the other table. If the [storeID] and [quantity] fields are available in the Fulfillment table, I recommend removing the Store table reference from the FROM clause (so "FROM Fulfillment" alone).
One last note: You mention that you want to count "orders". In some circumstances, an order may have multiple products and a quantity > 1. If your goal is the total number of "orders" regardless of the number of products or quantity of products on an order, you'll want to use "COUNT(DISTINCT orderID) as [Orders]" (where "orderID" is the reference to the unique order number).

Repeat a query over the parameter list

I would like to iterate the same query while using different parameter values from a predefined list.
Say, I have a table with two columns. The first columns contains customer name. The second column contains customer spending.
###CUSTOMER; SPENDING###
customer1; 1000
customer2; 111
customer3; 100
customer1; 323
...
I know the complete list of customers: customerlist = {customer1, customer2, customer3}.
I would like to do something like:
Select sum(spending)
from mytable
where customer = #customerlist
The query should compute the sum of spending for each customer defined in the customer list. I have found some examples of sql procedures with stored parameters but not the case with one parameter of multiple values.
Thank you
P.S. This is just a hypothetical example to illustrate my question (I know it would be much more effective to use here a simple group by).
You can use nested query like this
SELECT CustomerList.CustomerName Cust, isnull((SELECT SUM(Spending) CustSpending
FROM Customer
WHERE Customer.CustomerName = CustomerList.CustomerName),0)
FROM CustomerList
This would normally be done using GROUP BY:
Select customer, sum(spending)
from mytable
group by customer;
GROUP BY is a very fundamental part of SQL. You should review your knowledge of SQL so you understand how to use it.

MS Access - Identify duplicates having minimum value

I have a MS Access query which pulls [product name] and [price] along with several other fields. My problem is that I have multiple instances where [product name] is duplicated and [price] may or may not be the same between the duplicates. I'd like the query to show only one record for each of the duplicates and the minimum [price] associated with that [product name]....one big master list with no duplicates in it..... the final list should include all [product names] that didn't have duplicates and their associated price also.
I know this should be simple but for whatever reason I'm beating my brains out on it. I tried using a crosstab query already to return the minimum values for each unique [product name] but I have so many records that the crosstab query errors out on column count.
Any help would be greatly appreciated.
AC
MSAccess doesn't support Partition functions.
However, if you were able to get your data into a SQL database, you could easily do this using Window/Partition functions, which would allow you to do interesting things like select the cheapest 2 products, etc
SELECT *
FROM
(
SELECT ROW_NUMBER()
OVER (PARTITION BY [ProductName] ORDER BY [Price]) as RowNum, *
FROM Table
) X
WHERE RowNum = 1
You can now correctly get the actual row that was identified as the one with the lowest price and you can modify the ordering function to use multiple criteria, such as "Show me the latest product which had the cheapest score", etc.

Access query/SQL - duplicates in one field with distinct multiple 2nd field

I am working on a database with products and lot numbers. Each entry in the Lots table has a Lot Number and a Product description.
Sometimes there are multiple records of the same lot number, for example when an item is repacked a new record is created, but with the same Lot Number and same product description - this is fine. But other times there are problem cases, namely when two different products share the same Lot Number. I am trying to find those.
In other words, there are 3 possibilities:
Lot numbers for which there is only one record in the table.
Lot numbers for which there are multiple records, but the Product description is the same for all of them
Lot numbers for which there are multiple records, and the product descriptions are not all the same.
I need to return only #3, with a separate record for each instance of that Lot Number and product description.
Any help would be greatly appreciated.
Thanks Juan for the sample data. Using this example, I want to return the data contained in Id 2-8, but not 1, 9, 10, 11.
This wasn't easy because lot of time don't use access.
First select unique values using distinct.
Then count how many diferent product appear on each lotnumber using group by
Last join both result and show only the lots with more than one description where total >1
.
SELECT id, Product.lotnumber, Product.Product, total
FROM
Product Inner join
(
SELECT lotnumber, count(*) as total
FROM
(SELECT distinct lotnumber, product
FROM Product)
GROUP BY lotnumber
) SubT On Product.lotnumber = SubT.lotnumber
WHERE total > 1
ORDER BY id
As you can see :
lot 2 have two products (yy and zz)
lot 3 have thre products (aa, bb, cc)
I include my product table:
Sorry for spanish. Field types are Autonumeric, Short Text, and Number

JOIN on Access "Lookup" field returns no results

I have a strange problem that I believe is related to the way my lookups are structured.
TABLE Category
ID
CategoryName
TABLE Product
ID
ProductName
Category - Number (SELECT [Category].[ID], [Category].[Category Type] FROM Category ORDER BY [Category Type];)
TABLE SalePrices
Several fields related to sale date, price, &c.
ProductName - Text (SELECT [Product].[ID], [Product].[Product Name] FROM Product ORDER BY [Product Name];
For some reason I get a blank result set when I run the following query:
SELECT SalePrices.[Product Name], Product.[Product Name]
FROM SalePrices INNER JOIN Product ON SalePrices.[Product Name] = Product.[Product Name];
I have a query that displays the MIN of SalePrices.UnitPrice which I want to display with the ProductName and CategoryName, but I'm not getting results for that so I wanted to simplify things first.
When I join Product and Category I have to match Product.[Category Type] = Category.ID;, but when I try to do SalePrices.[Product Name] = Product.[ID]; I get a TYPE MISMATCH error. I'm not sure where I went wrong.
The eventual goal is to combine the SalesPrices <-> ProductName join with this one:
SELECT Product.[Product Name], Category.[Category Type]
FROM Product INNER JOIN Category ON Product.[Category Type] = Category.ID;
As suggested in the comments by #Scotch and #HansUp, defining "Lookup" fields in an Access table is generally regarded as a Bad Idea for all but the most trivial of cases. They hide what is really going in the database and they can lead to all kinds of confusion (as you have discovered) when you actually try to use them. (Ref: here, via comment by #HansUp.)
Your best course of action would be to replace the Lookup fields in your tables with regular numeric fields containing the ID (key) values in the related tables. Then, if necessary, you can create and save Select Queries to explicitly do the lookups and display the results as they previously appeared in the [Product] and [SalePrices] Datasheet Views.