If it helps, I'm using Opencart shopping cart & I am after showing an extra column in the reports-products-purchased page.
I can get it to display the quantity of items per category & also the total costs using the following code...
SELECT COUNT( DISTINCT op.model ) AS quantity, SUM( op.total + op.total * op.tax /100 ) AS total
FROM `order_product` op
LEFT JOIN `product_to_category` ptc
ON ( op.product_id = ptc.product_id )
WHERE ptc.category_id =192
OR ptc.category_id =177
GROUP BY category_id
this will display 7 items from a certain category totalling 135.00 & 5 items from the other category totalling 105.00
Quantity Total
7 135.00
5 105.00
But I am after displaying the name of the category from another table called category so that it displays like this
Category Quantity Total
Womens 7 135.00
Mens 5 105.00
I have tried linking the *product_to_category* to the category using LEFT JOIN, but i'm only a novice at this so any help would be great ;)
you just need to join on the category table and add your name.
SELECT c.name
, COUNT( DISTINCT op.model ) AS quantity
, SUM( op.total + op.total * op.tax /100 ) AS total
FROM order_product op
LEFT JOIN product_to_category ptc
ON op.product_id = ptc.product_id
LEFT JOIN category_description c
on ptc.category_id = c.category_id
WHERE ptc.category_id =192
OR ptc.category_id =177
GROUP BY ptc.category_id, c.name
Since you new to JOINs here is a helpful explanation of joins
A Visual Explanation of SQL Joins
Add the category description (whatever it's name is) to the select and the group by. You do not need the product_id in the group by if it is not included in the select.
SELECT ptc.CategoryDescription, COUNT( DISTINCT op.model ) AS quantity,
SUM( (op.total+op.total) * op.tax/100 ) AS total
FROM order_product op
LEFT JOIN product_to_category ptc ON ( op.product_id = ptc.product_id )
WHERE ptc.category_id =192
OR ptc.category_id =177
GROUP BY ptc.CategoryDesription
Related
Relationship Diagram
What I want to be able to do is return a query that shows the top 5 items/products on the menu for each of the 3 restaurants in the dataset. I've attached an example of the relationship diagram for some more context. The columns I would like to see in the query are:
RestaurantName
ItemName
NumberofOrders (alias column)
This is what I have at the moment but it doesn't work as expected for the top 5.
SELECT RestaurantName, ItemName, COUNT(Orders.OrderNumber) AS NumberofOrders
FROM ((((Restaurants INNER JOIN
Orders ON Restaurants.RestID = Orders.RestID) INNER JOIN
OrderDetails ON Orders.OrderNumber=OrderDetails.OrderNumber) INNER JOIN
Products ON OrderDetails.ItemID = Products.ItemID) INNER JOIN
FoodType ON Products.ProdTypeID = FoodType.ProdType)
WHERE ItemName IN
(SELECT TOP 5 ItemName
FROM Products
WHERE ItemName IS NOT NULL)
GROUP BY RestaurantName, ItemName
ORDER BY COUNT(Orders.OrderNumber) DESC;
This just repeats the same 5 items across all the restaurants. Any point in the right direction would be awesome.
EDIT 1:
Based on a response I got yesterday, I have made some amendments to the code. This the query is returning the full list, as though ignoring the top 5 in the subquery. I can see all the items are sorted by Total Orders (I have also changed the formula for this) Any ideas what I am doing wrong here?
SELECT RestaurantName, ItemName, SUM(Quantity)*COUNT(Orders.OrderNumber) AS TotalOrders
FROM ((((Restaurants INNER JOIN
Orders ON Restaurants.RestID = Orders.RestID) INNER JOIN
OrderDetails ON Orders.OrderNumber=OrderDetails.OrderNumber) INNER JOIN
Products ON OrderDetails.ItemID = Products.ItemID) INNER JOIN
FoodType ON Products.ProdTypeID = FoodType.ProdType)
WHERE ItemName IN
(SELECT TOP 5 p2.ItemName
FROM Products AS p2
WHERE p2.ItemName = Products.ItemName
GROUP BY p2.ItemName
ORDER BY COUNT(*) DESC)
GROUP BY RestaurantName, ItemName
ORDER BY RestaurantName, SUM(Quantity) DESC;
Thanks
You want a correlated subquery:
WHERE ItemName IN (SELECT TOP 5 p2.ItemName
FROM Products as p2
WHERE p2.RestaurantName = products.RestaurantName
GROUP BY p2.ItemName
ORDER BY COUNT(*) DESC
)
It seems really odd to me that a table called products would have a column called RestaurantName. But you claim that your query works and it has the same reference.
Your filter in the outer WHERE is only using the ItemName field. For your purpose it should contain both fields.
Like so:
SELECT
RestaurantName,
ItemName,
COUNT(Orders.OrderNumber) AS NumberofOrders
FROM Restaurants
INNER JOIN Orders ON Restaurants.RestID = Orders.RestID
INNER JOIN OrderDetails ON Orders.OrderNumber=OrderDetails.OrderNumber
INNER JOIN Products ON OrderDetails.ItemID = Products.ItemID
INNER JOIN FoodType ON Products.ProdTypeID = FoodType.ProdType
WHERE (RestaurantName, ItemName) IN
(SELECT TOP 5 RestaurantName, ItemName
FROM Products
WHERE RestaurantName IS NOT NULL)
GROUP BY RestaurantName, ItemName
ORDER BY COUNT(Orders.OrderNumber) DESC;
I have joined 3 tables for getting total revenue of each sub categories under electronics category.
But in output instead of getting specific revenue for each sub category I am getting one common value(total revenue generated by electronics category) for each sub category.
select prod_subcat as subcat, sum(total_amt) as total_revenue
from transection
left join customer_details
on transection.cust_id = customer_details.customer_ID
left join [dbo].[Product_cat_info]
on [dbo].[transection].[prod_cat_code] = [dbo].[Product_cat_info].[Prod_Cat_cod]
where Gender like 'M' and prod_Cat in (
select prod_Cat
from [dbo].[Product_cat_info]
where prod_Cat like 'Electronics'
)
group by [prod_subcat]
The output which I am getting is
subcat total_revenue
Personal Appliances 5702069
Mobiles 5702069
Computers 5702069
Audio and video 5702069
Cameras 5702069
Remove this subquery in IN causing more duplicates as you have already joined this table and replace this below query first also, add prod_cat to group by
prod_Cat in (select prod_Cat from [dbo].
[Product_cat_info]
where prod_Cat like 'Electronics')
with and prod_Cat like 'Electronics'
SELECT prod_subcat as subcat,
gender,
sum(total_amt) as total_revenue
from tbl_Tran T1
left join tbl_Cust C1
on T1.cust_id = C1.customer_ID
left join Prod_cat_info P1
on T1.prod_cat_code = P1.prod_cat_code
and T1.prod_subcat_code=P1.prod_sub_cat_code
where Gender like 'M' and prod_Cat in (
select prod_Cat
from Prod_cat_info
where prod_Cat like 'Electronics'
)
group by prod_subcat,Gender
Replace tbl_tran with transaction
and tbl_cust with customer
SELECT SUM(TOTAL_AMT) AS TOTAL_AMT , prod_subcat FROM DBO.prod_INFO AS A
LEFT JOIN DBO.Transactions AS B ON A.prod_cat_code =B.prod_cat_coDE AND A.prod_sub_cat_code
=B.prod_subcat_codE
LEFT JOIN DBO.Customer AS C ON B.cust_id = C.customer_Id
WHERE PROD_CAT IN ('ELECTRONICS') AND GENDER = 'M'
GROUP BY
prod_subcat
There is no need for inline subquery in WHERE statement.
I would like some help on this matter.
I Have three tables.
Products Table,
Invoice Table,
Cash Table
Products Table has 2 Columns as follows (PID,BRAND)
Invoice Table has 2 columns as follows (PID,TOTALSALES)
Cash Table has 2 columns as follows (PID,TOTALSALES)
The PID's could have many different BRANDS.
for eg:
PID BRAND
1 TEST1
2 TEST2
3 TEST3
All the three tables are linked by the PID column.
i have many rows in the invoice and cash tables.
My problem is to Group the SUMMED values of the TOTALSALES in the INVOICE and CASH tables BRAND wise.
I tried using left joins but the summation value always increases when there are more than 2 table in the join.
Any help will be highly appreciated.
You can use union all and then aggregate the results from the two tables together:
select p.brand, sum(invoice_sales) as invoice_sales, sum(cash_sales) as cash_sales
from ((select pid, totalsales as invoice_sales, 0 as cash_sales
from invoice i
) union all
(select pid, 0, totalsales
from cash c
)
) ic join
product p
on ic.pid = p.id
group by p.brand;
summarise the data in the Invoice and Cash tables separately
SELECT
pr.BRAND, (ISNULL(Inv.TOTALSALES, 0.00) + ISNULL(Csh.TOTALSALES, 0.00)) TotalSales
FROM Products pr
LEFT JOIN (
SELECT
PID, SUM(TOTALSALES) TOTALSALES
FROM Invoice GROUP BY PID
) Inv ON Inv.PID = pr.PID
LEFT JOIN (
SELECT
PID, SUM(TOTALSALES) TOTALSALES
FROM Cash GROUP BY PID
) Csh ON Csh.PID = pr.PID
ORDER BY pr.BRAND
You need two separate sums for the results of joining the tables by PID values and you will need to group the records by BRAND
select sum(Invoice.TOTALSALES) as invoice_sales, sum(Cash.TOTALSALES) as cash_sales
from Products
join Invoice
on Products.PID = Invoice.PID
join Cash
on Products.PID = Cash.PID
group by Invoice.PID, Products.BRAND;
If you do not need to group by products, then just omit Invoice.PID from the group by.
another way to do it is by using subquerys
select p.*,
(select sum(i.TOTALSALES) from Invoice i where i.PID = p.PID) as TotalSalesInvoice,
(select sum(c.TOTALSALES) from Cash c where c.PID = p.PID) as TotalSalesCash
from Products p
I have problems with some query. I need to get max value and product_name from that query:
select
products.product_name,
sum(product_invoice.product_amount) as total_amount
from
product_invoice
inner join
products on product_invoice.product_id = products.product_id
inner join
invoices on product_invoice.invoice_id = invoices.invoice_id
where
month(invoices.invoice_date) = 2
group by
products.product_name
This query returns a result like this:
product_name | total_amount
--------------+--------------
chairs | 70
ladders | 500
tables | 150
How to get from this: ladders 500?
Select product_name,max(total_amount) from(
select
products.product_name,
sum(product_invoice.product_amount) as total_amount
from product_invoice
inner join products
on product_invoice.product_id = products.product_id
inner join invoices
on product_invoice.invoice_id = invoices.invoice_id
where month(invoices.invoice_date) = 2
group by products.product_name
) outputTable
You can use order by and fetch first 1 row only:
select p.product_name,
sum(pi.product_amount) as total_amount
from product_invoice pi inner join
products p
on pi.product_id = p.product_id inner join
invoices i
on pi.invoice_id = i.invoice_id
where month(i.invoice_date) = 2 -- shouldn't you have the year here too?
group by p.product_name
order by total_amount
fetch first 1 row only;
Not all databases support the ANSI-standard fetch first clause. You may need to use limit, select top, or some other construct.
Note that I have also introduced table aliases -- they make the query easier to write and to read. Also, if you are selecting the month, shouldn't you also be selecting the year?
In older versions of SQL Server, you would use select top 1:
select top (1) p.product_name,
sum(pi.product_amount) as total_amount
from product_invoice pi inner join
products p
on pi.product_id = p.product_id inner join
invoices i
on pi.invoice_id = i.invoice_id
where month(i.invoice_date) = 2 -- shouldn't you have the year here too?
group by p.product_name
order by total_amount;
To get all rows with the top amount, use SELECT TOP (1) WITH TIES . . ..
If you are using SQL Server, then TOP can offer a solution:
SELECT TOP 1
p.product_name,
SUM(pi.product_amount) AS total_amount
FROM product_invoice pi
INNER JOIN products p
ON pi.product_id = p.product_id
INNER JOIN invoices i
ON pi.invoice_id = i.invoice_id
WHERE
MONTH(i.invoice_date) = 2
GROUP BY
p.product_name
ORDER BY
SUM(pi.product_amount) DESC;
Note: If there could be more than one product tied for the top amount, and you want all ties, then use TOP 1 WITH TIES, e.g.
SELECT TOP 1 WITH TIES
... (the same query I have above)
I need some help I have 3 tables
http://i.stack.imgur.com/TB3MX.jpg
My code:
select nazev_produkt,
SUM(mnozstvi_objednavka_dod)'bylo na sklade'
from Produkty p join Objednavky_dodavatele od on
p.id_produkt=od.id_produkt
where stavzbozi_objednavka_dod=('na skladě')
group by nazev_produkt
select nazev_produkt,SUM(mnozstvi_objednavka_zak)koupili
from Objednavky_zakaznici oz join Produkty p
on oz.id_produkt=p.id_produkt
where stav_objednavka_zak=('dodané')
group by nazev_produkt
I want to create select code from both of this selected which will consist of nazev_produkt, 'bylo na sklade - koupili' and group by nazev_produkt
basically
bylo na sklade = was in stock
koupili = purchased.
I need to deduct the purchased - was in stock and show nazev_produkt (Product Name), na sklade (In Stock)
Help is much appreciated!
I can't read your language, so making a few guesses here... :-) The table joining, I think, answers your question in any case.
select
p.product_name,
--isnull(i.quantity,0) as was_in_stock,
--isnull(s.quantity,0) as sold,
isnull(i.quantity,0) - isnull(s.quantity,0) as [currently_in_stock]
from
products p
LEFT JOIN (select product_id, sum(quantity) as quantity from inventory group by product_id) i
ON p.product_id = i.product_id
LEFT JOIN (select product_id, sum(quantity) as quantity from sales group by product_id) s
ON p.product_id = s.product_id
group by
product_name
Add a third column with the typization of your source.
Try this:
select nazev_produkt,
isnull(
(select SUM(mnozstvi_objednavka_dod)
from Objednavky_dodavatele od
where p.id_produkt=od.id_produkt),
0) -
isnull(
(select SUM(mnozstvi_objednavka_zak)
from Objednavky_zakaznici oz
where oz.id_produkt=p.id_produkt),
0)
from Produkty p
where stavzbozi_objednavka_dod=('na sklade')
or stav_objednavka_zak=('dodané')