SQL SUM problems - sql

I have this Query:
Select Denumire,Sum(Livrari.Cantitate)as Stoc,
isnull(Sum(Facturi_Emise.Cantitate),0) as 'Sold',
isnull(Sum(Livrari.Cantitate),0)-isnull(sum(Facturi_Emise.Cantitate),0) As 'Stoc After Sales',
Livrari.Id_Depozit
From Livrari
Left join Produse On Livrari.Id_Produs=Produse.Id_Produs
Left join Facturi_Emise On Produse.Id_Produs=Facturi_Emise.Id_Produs
group by Denumire, Livrari.Id_Depozit
order by Denumire
I need to get the Stock, the quantity of the items that are required to be sold, and what I got in the 2 deposits after the items are sold. But in the table "Livrari" I got the same item in both deposit, with the amount of 300 for deposit 1, and 300 for deposit 2 and when I make the sum and group by Id_Depozit I get that item with the amount of 600 in deposit 1 and 600 in deposit 2, same is for table Facutri_Emise as I should take only 250 items from deposit 1 and 300 from deposit 2, it takes 550(250+300) from both deposit and I got the Stoc after Sale 50 for each, instead of 50 for deposit 1 and 0 for deposit 2.
fiddle
My problem is that the result in row 8 and 9(that means Pahare) in column Stoc should be 300 for each. In next column Sold, row 8 should be 250 and for row 9 300. In the end, in column Stoc after Sale should be the difference, as row 8=50, row 9=0.
I mean each time a products repeats, my query is gonna make the sum and put the same value in deposit 1 and in deposit 2, as I give different values for each deposit it should show me the correspondent values. A supplier will bring a certain amount if items(let's say apples) into deposit 1 and another supplier will bring another amount of apples in deposit 2. When the bill is made("Facturi_Emise") for the client I should sent an amount of apples from deposit 1 and another from deposit 2 and I wanna see what amount remains in one deposit,and what remains in other one.

Here it is.
It is not ordered by deposit numbers,but it's okey.
SELECT Produse.Denumire,
Isnull(a.suma,0) AS Intrari,
Isnull(b.suma,0) AS Iesiri,
isnull(a.suma,0) - isnull(b.suma,0) AS Stoc
FROM Produse
LEFT JOIN
(SELECT ID_Produs, Sum(Cantitate) AS suma FROM Livrari GROUP BY ID_Produs)
AS a
ON Produse.ID_Produs = a.ID_Produs
LEFT JOIN
(SELECT ID_Produs, Sum(Cantitate) AS suma FROM Facturi_Emise GROUP BY ID_Produs)
AS b
ON Produse.ID_Produs = b.ID_Produs
SOLLUTION

Select Denumire,Sum(Livrari.Cantitate)as Stoc,
SUM(ISNULL(Facturi_Emise.Cantitate,0)) as 'Sold',
SUM(ISNULL(Livrari.Cantitate,0))-SUM(ISNULL(Facturi_Emise.Cantitate,0)) As 'Stoc After Sales',
Livrari.Id_Depozit
From Livrari
Left join Produse On Livrari.Id_Produs=Produse.Id_Produs
Left join Facturi_Emise On Produse.Id_Produs=Facturi_Emise.Id_Produs
and Livrari.Id_Depozit=Facturi_Emise.Id_Depozit
group by Denumire, Livrari.Id_Depozit
order by Denumire
You need ceck null before sum, soo first ISNULL and then SUM.
If you SUM and one is null then all SUM will be null.

Related

Can we change sub totals by filtering category?

I have a Category column where am showing grand total for Category.But now i want to filter total Category wise.Suppose if in front end i select 2 category then it should show that two categories total , if i select 3 then it should be 3 categories total.
If it is possible then please let me know.
Portfolio Product Revenue
Total NULL 600
First P1 100
Second P2 200
Third P3 100
Fourth P4 200
In front end if i will select First and Second Portfolio then Total value should come 300.Like that if i select any combination it show that level addition.
Use SUM together with IN for filtering
SELECT SUM(revenue)
FROM someTable
WHERE portfolio IN ('First', 'Second')

SQL select statement similar to vertical search approximate match in Excel

Having a table with columns 'price' and 'quantity'.
e.g:
rec price qty
1. 10,00 1
2. 7,50 5
3. 5,00 25
4. 3,00 100
I need to select the price for a quantity of 65. This is the price of record 3. Qty 65 is between qty 25 and 100. How to solve this in a sql query?
You can solve that with an inner SQL statement which tries to find the highest quantity lower than or equal to your requested quantity of 65:
select pce.price
from prices pce
join ( select max(qty) qty
from prices
where qty <= 65
) pce2
on pce.qty = pce2.qty
Here pce2 is the join to match the prices line. The pce table is joined to have access to all fields joined. This will only work correctly if there are no duplicates in prices for qty.

SQL Group by prevents summing across multiple records

I am trying to sum the amount paid across multiple entries in the Payment table and show who the buyers were for that Order
so if two people made payments on one order it would show their combined payments and show who the people who made the payment were. So if Bob and Sue made 10 dollar payments on a 30 dollar bill it would show
Order Buyer Paid Owes
1 Bob 20 10
1 Sue 20 10
but i'm currently at
Order Paid Owes
1 20 10
How do I add in the buyers? possibly with a join?
Currently I have.
Select Order.Orderid, sum(Payment.amount) as "Paid", Order.Price-sum(Payment.amount) as "Owes"
from order, payment
where payment.orderId = order.orderid
group by (order.orderid, order.price)
payment has a buyerId and orderid as foreign keys since it is an m to n relation.
As you mention in your comment when you join the buyer it does not give you the desired output which is the sum of all payments. To get the buyers and the sum of all payments joining another instance of the payments table and using that to calculate the sum will do the trick.
SELECT
Order.Orderid,
Buyer.Name,
SUM(PaymentSum.amount) AS 'Paid',
Order.Price-SUM(PaymentSum.amount) AS 'Owes',
FROM
Order
JOIN Payment
ON Order.Orderid = Payment.Orderid
JOIN Buyer
ON Payment.BuyerId Buyer.BuyerId
JOIN Payment AS PaymentSum
ON Order.Orderid = PaymentSum.Orderid
GROUP BY
Order.Orderid,
Order.Price,
Buyer.Name

Query to return zero if nothing exist

I have a table with currency, paymenttype and invoiceamount. I have to write query to get currency, paymenttype and total invoiceamount made. This is pretty simple with group by. But actually I have three payment type 0, 1 ,2 and data in table is
Currency. Paymenttype invoice amount
Aaa. 0. 100
Aaa. 1. 200
Aaa. 1. 50
Bbb. 0. 150
Bbb. 1. 100
Bbb. 2. 100
My query is Select currency, paymenttype, sum(invoiceamount) as total from table group by currency, paymenttype
Result
Currency paymenttype total
Aaa. 0. 100
Aaa. 1. 250
Bbb. 0. 150
Bbb. 1. 100
Bbb. 2. 100
But what I want is as Aaa. Does not have 2 paymenttype is should also show a row with 0 value like below.
Aaa. 2. 0
How to do this?
You can generate all the rows using a cross join and then join in the data you want:
select c.currency, pt.paymenttype,
coalesce(sum(i.invoiceamount), 0) as total
from currency c cross join
paymenttype pt left join
invoice i
on i.currency = c.currency and i.paymenttype = pt.paymenttype
group by c.currency, pt.paymenttype;
You should have a table containing all the types.
Then you would simply do a left join on the payment_type_id an output the total, or 0 if nothing.
If you don't have a table with all the types, then you could simulate it but that would be a dirty fix :
select a.currency, b.paymenttype, coalesce(sum(a.invoiceamount), 0)
from (select 0 as paymenttype,
union all select 1 as paymenttype,
union all select 2 as paymenttype) b
left join yourTable a on a.paymenttype = b.paymenttype
group by a.currency, b.paymenttype;

MySQL - Finding out Balancing Figure From 2 Tables

I have 2 tables like this:
Stock Table
product_id bigint(20)
qty float
Sales Table
product_id bigint(20)
qty float
Sample Data
Stock Table
product_id---qty
1---10
2---11
3---20
4---50
1---10
3---10
Sales Table
product_id---qty
1---2
2---5
3---20
4---40
1---7
I want the following Output after running the Query
product_id---qty
1---11
2---6
3---10
4---10
Well, as spender ask I am trying to more clear the situation.
First of All, let's think that I store
10 quantity of product 1
11 quantity of product 2
20 quantity of product 3
50 quantity of product 4
10 quantity of product 1 (now I have total 20 of product 1)
10 quantity of product 3 (now I have total 30 of product 3)
Secondly, let's think that I sell
2 quantity of product 1
5 quantity of product 2
20 quantity of product 3
40 quantity of product 4
7 quantity of product 1 (now I have sold total 9 of product 1)
Thirdly, I want to know how much stock is now in my hand
11 quantity of product 1 (20-9 = 11)
6 quantity of product 2 (11-5 = 6)
10 quantity of product 3 (30-20 = 10)
10 quantity of product 4 (50-4 = 10)
My Question is: To find out this stock what is the Query?
Thanks in Advance for answering my question.
This answer works in Oracle - don't have MySql so can't test there
select product_id, sum(qty) from
(
select product_id, qty from stock
union all
select product_id, (-1 * qty) from sales
) as a
group by prod
You question is lacking detail and looks like it might even contain typos in the presented data. I'm going to make the assumption you are trying to calculate the diff between stock quantities and sales quantities, despite your data not actually supporting this (!!!). It looks like you require the following:
select
st.product_id,
sto.qty-st.qty
from
salesTable as st
join stockTable as sto on sto.product_id=st.product_id
Chris's answer is absolutely correct. But for the information I want to add this one which I found on NET.
SELECT tunion.product_id, (
(IFNULL((SELECT SUM(s.qty) FROM stock s WHERE s.product_id=tunion.product_id),0))-
(IFNULL((SELECT SUM(p.qty) FROM sales p WHERE p.product_id=tunion.product_id),0)))
AS quantity
FROM (SELECT DISTINCT s.product_id FROM stock s
UNION ALL SELECT DISTINCT p.product_id FROM sales p)
AS tunion GROUP BY tunion.product_id