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

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

Related

SQL using result from select from clause to join another table

I am working on a legacy app, I am still learning SQL and would consider my SQL knowledge as beginner.
I have 2 tables, one is a receipt type structure containing receipt no, a docket number (plus other info regarding total etc) and a car rego number.
there are the potential for multiple receipts for a car ie multiple matches on rego number
The second has a listing of the items related to that receipt (description, partno, time) each of the items are related by docketnumber - the "registerhistory"
multiple items appear as multiple rows (with same docketnumber) in the "registerhistory" and also items of the same type are not stored as a qty but as duplicated rows in the table with the same docket number each have a price stored
I am trying to generate a report based upon a search match on rego number and create a join to the matching tableregister items and list them (with hopefully an end goal of grouping any duplicate items into a qty and subtotal)
This is an access database if that changes the syntax
I am unclear on how I can take the results of one select query and use these results to create a join or there might be a better approach
So I need to firstly locate all receipts with a matching rego number, with those receipts, find the associated items (by docket number) hopefully group the items like so
receipt no 1
Item1 with multiples as qty with subtotal
Item2
Item3
receipt no 2
Item1
Item2 with multiples as qty with subtotal
Item3
Any help greatly appreciated,
(SELECT * from tblreceipts
where vehicle = 'abc123')
join tblregisterhistory on
tblreceipts.docketnum = tblregisterhistory.docketnum
I can even get to linking the results from the select query to a join, let alone get to my desired end result.
Are you trying to simply do a JOIN and GROUP BY? Something like this:
select partno, count(*) as qty
from tblreceipts as r inner join
tblregisterhistory as rh
on rh.docketnum = r.docketnum
where r.vehicle = 'abc123'
group by partno;
Ok with a bit of study and some helpful hints above. I have this (also apologies for the code formatting, still familiarising myself with the stack posting techniques)
SELECT vehicle, tblregisterhistory.date, partnumber, count(partnumber) as qty,
description, sum(price) as subtotal
FROM TBLRECEIPTS INNER JOIN
tblregisterhistory ON tblreceipts.docketnumber =
tblregisterhistory.docketnumber where tblreceipts.vehicle = 'abc123' group by
tblregisterhistory.date, vehicle, partnumber, description, price

Oracle SQL: Show Individual Count Even if There are Duplicates

this is my first question on here, so please forgive me if I break any rules.
Here is what I need to know:
How do I create an Oracle SQL query that will display a unique count of something even if there are duplicates in the results?
Example: a customer table has a list of purchases made by various customers. The table lists the customer ID, name, category of purchase (ie Hardware, Tools, Seasonal) ect. The outcome of the query needs to show each customer id, customer name and the category of the purchase, and a count of the individual customer. SO customer ID 1 for John Smith has made a purchase in each department. If I do a count of the customer, he will appear three times as he has made three purchases, but I also need a column to count the customer only once. The count in the other rows returned for the other departments should show a 0 or Null.
I normally achieve this by pulling everything and exporting to excel. I add a column that uses an IF formula on the ID to only show a 1 on the first occurrence of the customer IE: IF(A3=A2,0,1) (if a3 is the same as A2, show a 0, if it's not the same as A2 then show a 1). This will give me a unique count of customers for one part of the report and will still show me how many purchase the customer made in another part of the report.
I want to do this directly in the SQL query as I have a large set of data this needs to be done on, and adding any formulas in excel will make the sheet huge. This will also make it easier to host the query results in ACCESS so excel can pull it from there.
I have tried to find a solution to this for a while, but any searching on Google will usually return results on how to remove duplicates form a table or how to count the duplicates in a table.
I am sorry if this is long question, but I wanted to be through so I do not waste anyone's time on back an fourth comments (I have seen this many times on here and else where when the OP asks a very cryptic question and expects everyone to understand them without further expiation).
Using distinct can be used in a count to only count the unique values of a field.
SELECT
cust.customer_id, cust.customer_name, p.category,
count(distinct p.department_id) as total_departments,
count(*) as total_purchases
FROM customers cust
LEFT JOIN purchase_table p on (cust.customer_id = p.customer_id)
GROUP BY cust.customer_id, cust.customer_name, p.category
ORDER BY cust.customer_id;
Such method is not limited to the Oracle RDBMS.

SQL query - select only products ids which was sorted top in another table

Ok, I have situation where I need to create SQL query which will return for me ids from table1 (products) which was ordered by table2 (category) and limited by 10 for each category.
So, what I need. Select product ids which was appeared on "top 10" (limited by 10) results in each category after ordering of those products. Each product has some columns and I order by those columns. The same product can appear on different categories on top 10, for example. So I need use distinct for uniq results.
Is there any relationship between Product and Category? What at the Product columns you're ordering by? Is it ok for there to be duplication between different lists of products? You should really post you models/sql tables and more clearly explain what you're trying to do if you want real help.
Assuming they're many-to-many/the relationships are set up in rails and having the same products in multiple lists is ok I would do something like this
top_products = {}
Category.all.each do |cat|
top_products[cat.name] = cat.products.order("some_product_column DESC").limit(10).map{|p| p.id}
end

Retrieving average cost

UPDATE: yes, the result is for a single record. I want to put this on a "computed by" field in firebird (PRODUCTS.PRODU_AVGCOST). It just takes the last 3 buyings for a product and calculates the average cost of it.
I have three tables, witch follows the revelant fields:
PRODUCTS
PRODU_ID PK,
PRODU_AVGCOST calculated
BUYINGS
BUYIN_ID PK
BUYING_ITENS
ITEN_ID PK,
ITEN_BUYING_ID FK
ITEN_COST numeric
I want to take the average cost of last three buyings from ITEN_COST field, using "select" for the PRODU_AVGCOST field of the PRODUCTS table
I tried as follows on table PRODUCTS, but this didn't work
select avg(iten_cost) from buying_itens b
where (select first 3 (iten_cost) from buying_itens where c.iten_id = produ_id)
order by b.iten_id desc
Assuming you want this for a single product (assuming ACTUAL_PRODU_ID is that value), you can do:
select avg(a.iten_cost)
from (
select first 3 iten_cost
from buying_itens
where produ_id = ACTUAL_PRODU_ID
order by iten_id desc
) a
As far as I can tell the datamodel in your question is not complete (or I fail to see how products and buying_itens are linked), so I have 'added' produ_id to buying_itens.
If you want to do this for all products in a single query, things get more complicated.

How to count unique records and get number of these uniques in table using SQL?

Imagine I have table like this:
id:Product:shop_id
1:Basketball:41
2:Football:41
3:Rocket:45
4:Car:86
5:Plane:86
Now, this is an example of large internet mall, where there are shops which sell to one customer, so customer can choose more products from each shop and buy it in one basket.
However, I am not sure if there is any SQL syntax which allows me to simply get unique shop_ids and total number of those shops' products in customer basket. So I'd get something like:
Shop 41 has 2 products
Shop 45 one product
Shop 86 two product
I can make SQL queries to scoop through table to make some kind of ['shop_id']['number_of_products'] array variable that would store all products' shop_ids, then "unique them" - up and count how many times I had to cut one more shop_id out to have some remaining but that just seems as a lot of useless scripting.
If you got some nice and neat idea, please, let me know.
This is exactly the sort of thing that aggregate functions are for. You make one row of output for each group of rows in the table. Group them by shop_id and count how many rows are in each group.
select shop_id, count(1) from TABLE_NAME
group by shop_id