Lookup with duplicate values - sql

This is kind of a complicated question. I have three tables:
A PRODUCTS table
ProductID
ProductName
Product A
Edwardian Desk
Product B
Edwardian Lamp
And a GROUPS table
ProductGroup
ProductID
Group A
Product A
Group A
Product B
Group B
Product C
And a SALES table
Product ID
Sales
Product A
1000
Product B
500
And I need to show the total of Sales per Product Group.
This part I understand; I wrote the query:
SELECT Groups.ProductGroup, SUM(Sales) AS TotalSales
FROM Groups
JOIN Sales
ON Groups.ProductID=Sales.ProductID
GROUP BY Groups.ProductGroup
This is the part that confuses me though: for each group, I need to pull in one of the names of the products in the group. However, it does not matter which name is pulled. So the final data could show:
Group A, Edwardian Desk, 1500
or
Group A, Edwardian Lamp, 1500
How can I pull the name of the product into my query?
I am working in Microsoft SQL Server

There's a number of ways to bring in one of your product's names, a couple of options are to either use an aggregation with a correlated subquery or to to use an apply.
Note, I've used aliases for your table names - doing so is good practice and makes queries more compact and easier to read. Also - presumably this is a contrived example and not your actual tables - but generally it's not a good practice to have column names identical to the table name, so if Sales on table Sales represents a quantity, then just call it Quantity!
select g.ProductGroup,
(select Min(ProductName) from Products p where p.ProductId=g.ProductId) FirstProductAlphabetically,
Sum(s.Sales) as TotalSales
from Groups g
join Sales s on s.ProductID=g.ProductID
group by g.ProductGroup
select g.ProductGroup,
p.ProductName as FirstProductById,
Sum(s.Sales) as TotalSales
from Groups g
join Sales s on s.ProductID=g.ProductID
cross apply (
select top (1) p.ProductName
from Products p
where p.ProductId=g.ProductId
order by ProductId
)p
group by g.ProductGroup

You can add products to the JOIN and use an aggregation function:
SELECT g.ProductGroup, SUM(s.Sales) AS TotalSales,
MIN(p.ProductName)
FROM Groups g JOIN
Sales s
ON g.ProductID = s.ProductID JOIN
Products p
ON p.ProductID = s.ProductId
GROUP BY g.ProductGroup;
Note: I often add two columns, MIN() and MAX() to get two sample names.
I should add. Your sample data has ProductIds that are not in the Products. That suggests a problem with either the question (more likely) or the data model. If you actually have references to non-existent products, then use a LEFT JOIN to Products rather than an inner join.

Related

SQL - Create complete matrix with all variables even if null

please provide some assistance/guidance to solve the following:
I have 1 main table which indicates sales volumes by sales person per different product type.
Where a salesperson did not sell a particular product on a particular day, there is no record.
The intention is to create null value records for salesmen that did not sell a product on a specific day. The query must be dynamic as there are many more salesmen with sales over many days.
Thanks in advance
Just generate records for all sales persons, days, and products using cross join and then bring in the existing data:
select p.salesperson, d.salesdate, st.salestype,
coalesce(t.sales_volume, 0)
from (select distinct salesperson from t) p cross join
(select distinct salesdate from t) d cross join
(select distinct salestype from t) st left join
t
on t.salesperson = p.salesperson and
t.salesdate = d.salesdate and
t.salestype = st.salestype;
Note: You may have other tables that have lists of sales people, dates, and types -- and those can be used instead of the select distinct queries.

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 calculation issue

I am trying to find the cost per category by joining two tables
I have wrote this query, but it seems to place the same resulting value for all categories.
SELECT category,
(select sum(count(partid) * p.cost)
from PARTS p join order_line o using (part_id)
group by category, p.cost)
from parts p join order_line o using (part_id)
group by category
Table structure:
Parts:PartID#,description,manu_date,manu_id,cost,retai,discount,category
Order_line: Order#,item#,PartID,manu_id,unitprice,quantity
What I am trying to accomplish is i want to times the cost per parts table, with the count of (quantity*partid) in the order_line table to find out which category has the highest cost.
I am using oracle 11g
your subquery isn't correlated with the embedding sql, therefore its result is the same for each category.
You do not need to weigh the part costs with the number of orders, this will happen implicitly through the join:
SELECT category
, sum (p.cost * o.quantity)
FROM parts p
JOIN order_line o USING (partid)
GROUP BY category
;

Oracle SQL - Problem displaying using the foreign key

I am trying to display all of the products showing the dates they have been sold but also all of the products that haven't been sold either.
I have two tables: Products and Sales. The column names are:
Products
prod_id
prod_name
Sales
prod_id
date_of_sale
The two tables are linked using the prod_id column but I just cant seem to get the products that have not been sold to display as well as the ones with sales.
I think you need to use a left outer join between Products and Sales:
SELECT p.PROD_ID, p.PRODUCT_NAME, s.DATE_OF_SALE
FROM PRODUCTS p
LEFT OUTER JOIN (SELECT DISTINCT PROD_ID, DATE_OF_SALE
FROM SALES) s
ON (s.PROD_ID = p.PROD_ID)
Can't play with it at the moment but I think that should get what you want. You should get all PROD_ID's and PRODUCT_NAME's from PRODUCTS, and all DATE_OF_SALE from SALES. If there are no DATE_OF_SALE for a product, you should still see the product.
Share and enjoy.
SELECT p.prod_id, p.product_name, s.date_of_sale
FROM products p
, sales s
WHERE s.prod_id(+) = p.prod_id
;

MySQL multiple table count query

I have 3 tables
products
productid (int)
name (varchar)
price (float)
sales
salesid (int)
productid (int)
time (datetime)
links
linkid (int)
productid (int)
link (text)
Now I need a query that can display as
ProductID ProductName Sales Links
1 ABC 10 8
2 XYZ 15 12
I need all sales count and all links count for a particular product
How can I achieve this?
Thanks
SELECT p.productid, p.pname AS ProductName,
Count(DISTINCT s.salesid) as Sales, Count(DISTINCT l.linkid) as Links
FROM products p
LEFT JOIN sales s ON p.productid=s.productid
LEFT JOIN links l ON p.products=l.productid
GROUP BY p.productid
You need to write a cross-tab query.
This walk-through on the mysql site should help.
Or like in this tutorial
You can only use aggregate functions (like Count()) on the column specified in the GROUP BY clause, otherwise the aggregation is ambiguous. See the chapter "Ambiguous Groups" from the excellent book SQL Antipatterns for more reference.
In your case, the best option is to use two sub-queries:
SELECT p.productid as ProductID, p.pname AS ProductName,
(SELECT Count(*) FROM sales s WHERE p.productid=s.productid) as Sales,
(SELECT Count(*) FROM links l WHERE p.productid=l.productid) as Links,
FROM products p
GROUP BY p.productid
Not the most efficient query ever written, but it's perfectly ok as long as the tables doesn't contain a huge number of rows and/or you run it as a periodic report and not real-time on live data.
The best thing to do is to test it for yourself and see if the performance is acceptable.