0

In my SQLite I have the following tables:

Products:
Pro_id.    Pro_name
1.        Item1
2.        Item2
3.        Item3
4.        Item4

Purchases:
Pro_id.  Pur_Qty   Pur_Price
1.        10.        10
1.        10.        11
2.        20.        10
2.        10.        12
..        ..         ..

Sales:
Pro_id.    Sa_Qty.     Sa_price
1.          10.          15
1.          10.          20
2.          20.          15
2.          10.          25

Now i want:

1- to show product ID and product name from products.
2- i want to sum avg prices from both tables sales & purchases and show it.
3- i want to sum profits for all products every product must have it's profits ..

How to do that?

I tried this :

select
 pro_name,
 sum(sa_qty)* (sum(sa_qty*sa_price)/sum(sa_qty)) -
     sum(sa_qty)*(sum(pur_qty*pur_price)/sum(pur_qty)) as Profits

from products 
left join purchases on purchases.pro_id= products.pro_id 
left join sales on sales.pro_id = products.pro_id 

group by pro_name 
having sales.pro_id

2 Answers 2

1

As a variant:

select
   products.pro_id,
   products.pro_name,
   (select avg(pur_price) from purchases where purchases.pro_id=products.pro_id) +
      (select avg(sa_price) from sales where sales.pro_id=products.pro_id)
      as sum_of_average,
   (select sum(sa_price*sa_qty) from sales where sales.pro_id=products.pro_id) -
      (select sum(pur_price*pur_qty) from purchases where purchases.pro_id=products.pro_id)
      as profits
from products
2
  • That is not what I want but your answer made me to understand how to use queries in SQLite I will post my final solution thanks Commented May 25, 2023 at 15:32
  • And this saved me a lot now i solved 3 problems in my in my project 👍 Commented May 25, 2023 at 15:38
0
select
   products.p_id,
   products.p_name,
   (select avg(sa_price) *
   sum(sa_quantity) from sales where sales.pro_id=products.p_id)
   -
      (select avg(pur_price) from purchases where purchases.pro_id=products.p_id)
      *
      (select sum(sa_quantity) from sales where sales.pro_id=products.p_id) as Profits
      
from products group by products.p_name
4
  • You do not need group by here. Grouping is done already in subselects.
    – White Owl
    Commented May 25, 2023 at 21:34
  • Ah ok thanks i just see that when using group by name it groups them alphabeticaly Commented May 26, 2023 at 19:39
  • No. Sorting has nothing to do with group by, If you want sorting, use order by.
    – White Owl
    Commented May 26, 2023 at 23:35
  • Ah ok thanks 🙏😊 Commented May 27, 2023 at 20:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.