MySQL - Want to Minus two SUM() values from two SELECT statements - mysql

I want to be able to grab the two values that I have generated in SUM() from two SELECT queries and minus these values in order to get the result (OutstandingFunds).
These are my two SELECT queries:
Statement (1):
SELECT SUM(Cf.Amount) AS ClearedFunds
FROM (
SELECT Amount FROM PAYMENT1 WHERE `Status` = "Cleared"
UNION ALL
SELECT Amount FROM PAYMENT2 WHERE `Status` = "Cleared"
UNION ALL
SELECT Amount FROM PAYMENT3 WHERE `Status` = "Cleared") AS Cf;
Statement (2):
SELECT SUM(Price) AS TotalSales
FROM PROPERTY
WHERE Status = “Sold”;
Thank you for your time

If you don't need to show the separate subtotal for total sales and cleared funds, you can do it like this:
SELECT SUM(Total.`Price`) AS ClearedFunds
FROM (
SELECT `Price` FROM PROPERTY WHERE `Status` = 'Sold'
UNION ALL
SELECT (`Amount` * -1) AS `Price` FROM PAYMENT1 WHERE `Status` = 'Cleared'
UNION ALL
SELECT (`Amount` * -1) AS `Price` FROM PAYMENT2 WHERE `Status` = 'Cleared'
UNION ALL
SELECT (`Amount` * -1) AS `Price` FROM PAYMENT3 WHERE `Status` = 'Cleared'
) AS Total;
I am assuming you are wanting to subtract cleared funds from total sales here.

You were almost there... here's the working SQL:
SELECT (SELECT SUM(Cf.Amount) AS ClearedFunds
FROM (
SELECT Amount FROM PAYMENT1 WHERE `Status` = "Cleared"
UNION ALL
SELECT Amount FROM PAYMENT2 WHERE `Status` = "Cleared"
UNION ALL
SELECT Amount FROM PAYMENT3 WHERE `Status` = "Cleared") as Cf)
- (SELECT SUM(Price) AS TotalSales
FROM PROPERTY
WHERE Status = "Sold") as Result;
Here's the SQL Fiddle so that you can play with test data: http://sqlfiddle.com/#!2/18677/11

You can use SELECT ... INTO ..., in your case:
SELECT SUM(Cf.Amount) AS ClearedFunds
FROM (
SELECT Amount FROM PAYMENT1 WHERE `Status` = "Cleared"
UNION ALL
SELECT Amount FROM PAYMENT2 WHERE `Status` = "Cleared"
UNION ALL
SELECT Amount FROM PAYMENT3 WHERE `Status` = "Cleared") INTO #cf;
SELECT SUM(Price) AS TotalSales
FROM PROPERTY
WHERE Status = “Sold” INTO #ts;
Then you can substract or use them in any other query, like this:
SELECT #ts - #cf;

Are you looking for this?
SELECT C.ClearedFunds - P.TotalSales
FROM (
SELECT SUM(Cf.Amount) AS ClearedFunds
FROM (
SELECT Amount FROM PAYMENT1 WHERE `Status` = "Cleared"
UNION ALL
SELECT Amount FROM PAYMENT2 WHERE `Status` = "Cleared"
UNION ALL
SELECT Amount FROM PAYMENT3 WHERE `Status` = "Cleared") AS Cf) C,
(SELECT SUM(Price) AS TotalSales
FROM PROPERTY
WHERE Status = “Sold”) P
;

Related

MySQL - Add values to the IN clause?

I am currently have this query:
SET sql_mode='';
SELECT `id`, `url`,`number`,`abbrev`,`content`,`label`,`hier-1` FROM `leganalyse_unitsub_2020` WHERE `id` IN (SELECT MAX(`id`) FROM `leganalyse_unitsub_2020` GROUP BY `url`)
The subquery in the following clause:
SELECT MAX(`id`) FROM `leganalyse_unitsub_2020` GROUP BY `url`
returns a set of integer values.
For each integer value returned x, I'd like to also include x-1, x-2, x-3, x-4 and x-5.
So something like:
SELECT `id`, `url`,`number`,`abbrev`,`content`,`label`,`hier-1` FROM `leganalyse_unitsub_2020` WHERE `id` IN
(
SELECT MAX(`id`) FROM `leganalyse_unitsub_2020` GROUP BY `url`
UNION
SELECT MAX(`id`)-1 FROM `leganalyse_unitsub_2020` GROUP BY `url`
UNION
SELECT MAX(`id`)-2 FROM `leganalyse_unitsub_2020` GROUP BY `url`
UNION
SELECT MAX(`id`)-3 FROM `leganalyse_unitsub_2020` GROUP BY `url`
UNION
SELECT MAX(`id`)-4 FROM `leganalyse_unitsub_2020` GROUP BY `url`
)
But I am not sure if this is correct.
What query will do what I have described?
Cross join the subquery with a query that returns 0, 1, 2, 3, 4 to get all the possible values:
SELECT id, url,number, abbrev, content, label, hier-1
FROM leganalyse_unitsub_2020 WHERE id IN (
SELECT g.id - t.id
FROM (SELECT 0 id UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4) t
CROSS JOIN (SELECT MAX(id) id FROM leganalyse_unitsub_2020 GROUP BY url) g
)
This code is based on your last query.
If you want the values to be like x-1, x-2, x-3, x-4 and x-5 as you mention in the question the you should use this subquery:
SELECT 1 id UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5

Mysql clear code in one line

i was searching on google and in stackoverflow.com how can i write this code clearly and nice but found nothing.
Any idea?
MySQL query:
SELECT COUNT(*) AS `allInvoice`,
(SELECT COUNT(*) FROM `ocr_entity` WHERE `status` = 0) AS `new`,
(SELECT COUNT(*) FROM `ocr_entity` WHERE `status` = 10) AS `notTemplate`,
(SELECT COUNT(*) FROM `ocr_entity` WHERE `status` = 50) AS `withMistake`,
(SELECT COUNT(*) FROM `ocr_entity` WHERE `status` = 100) AS `finished`,
(SELECT COUNT(*) FROM `ocr_entity` WHERE `status` = 200) AS `skipped`
FROM `ocr_entity`;
Use conditional aggregation:
SELECT COUNT(*) AS `allInvoice`,
SUM( `status` = 0 ) AS `new`,
SUM( `status` = 10 ) AS `notTemplate`,
SUM( `status` = 50 ) AS `withMistake`,
SUM( `status` = 100 ) AS `finished`,
SUM( `status` = 200 ) AS `skipped`
FROM `ocr_entity`;
MySQL treats booleans as numbers in a numeric context, with 0 for false and 1 for true (which is why SUM() works).

Sum only if all grouped rows are not null, else return null

I have a table like this:
item_id quantity
1 2
1 3
2 NULL
2 4
3 NULL
3 NULL
And now I'm doing a SELECT like this:
SELECT
sum(`quantity`) AS `total_quantity`,
FROM `items`
GROUP BY `item_id`
Now, it return repectively 5, 4, and NULL, but I want 5, NULL and NULL.
I want that if there is a NULL value in the grouped rows, the sum should be NULL, and not the sum of the lines whose columns are not null. How can I achieve that?
Thanks!
You can use only case statement to check if any row of a group contains null as quantity
SELECT item_id,
CASE WHEN SUM(quantity IS NULL) > 0
THEN NULL
ELSE SUM(quantity)
END quantity
FROM items
GROUP BY item_id
using #Abhik Chakraborty's fiddle
DEMO
Thats kind if weird output, in most cases the request is to replace null with 0 or something else, however here is a way to do it
select
x.item_id,
max(x.quantity) as quantity from (
SELECT
t1.item_id,
#sm:= if(#prev_item = item_id, #sm_qty+quantity,quantity) as quantity,
#prev_item :=item_id,
#sm_qty:= quantity
from items t1,(select #prev_item:=null,#sm_qty=0)x
order by item_id
)x
group by x.item_id;
http://www.sqlfiddle.com/#!9/ccb36/13
SELECT * FROM (
( -- Get all not null quantities
SELECT
`i1`.`item_id`,
sum(`i1`.`quantity`) AS `total_quantity`
FROM `items` AS `i1`
WHERE `i1`.`item_id` NOT IN ( SELECT `i2`.`item_id` FROM `items` AS `i2` WHERE `i2`.`quantity` IS NULL )
GROUP BY `item_id`
)
UNION ALL
( -- Get all null quantities
SELECT
`i3`.`item_id`,
null AS `i3`.`total_quantity`
FROM `items` AS `i3`
WHERE `i3`.`item_id` IN ( SELECT `i4`.`item_id` FROM `items` AS `i4` WHERE `i4`.`quantity` IS NULL )
GROUP BY `i3.item_id`
)
) AS items_table
ORDER BY items_table.item_id

MySQL SELECT Query - Subtract a SUM() value with the combined total of two other SUM() values

I have two SELECT statements that give the values "TotalSales" and "VendorPay_Com". I want to be able to subtract VendorPay_Com from TotalSales within the one MySQL statement to get the value "Outstanding_Funds" but I haven't found a reliable way to do so.
These are my two statements:
Query 1:
SELECT SUM(Price) AS TotalSales
FROM PROPERTY
WHERE Status = 'Sold';
Query 2:
SELECT SUM(AC.Amount) AS VendorPay_Comm
FROM (
SELECT Amount FROM lawyer_pays_vendor
UNION ALL
SELECT CommissionEarned AS `Amount` FROM COMMISSION AS C WHERE C.`status` = 'Paid') AS AC
Any help on this matter would be greatly appreciated :)
You can do it as follows :
select (select ...) - (select ...)
In your example, simply :
select
(
SELECT SUM(Price) AS TotalSales
FROM PROPERTY
WHERE Status = 'Sold'
)
-
(
SELECT SUM(AC.Amount) AS VendorPay_Comm
FROM (
SELECT Amount FROM lawyer_pays_vendor
UNION ALL
SELECT CommissionEarned AS `Amount` FROM COMMISSION AS C WHERE C.`status` = 'Paid') AS AC
) AS Outstanding_Funds
Try
SELECT TotalSales-VendorPay_Comm AS Outstanding_Funds
FROM
(SELECT SUM(Price) AS TotalSales
FROM PROPERTY
WHERE Status = 'Sold') t1,
(SELECT SUM(Amount) AS VendorPay_Comm
FROM (SELECT Amount FROM lawyer_pays_vendor
UNION ALL
SELECT CommissionEarned AS Amount
FROM COMMISSION
WHERE Status = 'Paid') t0) t2
Here is sqlfiddle

where clause while joining select

I need to get payment sum for all period and for current month. There are two tables: category and transactions.
transactions:
id int(11)
category varchar(32)
dttm_added datetime
minus float
minus_currency varchar(32)
categories:
id int(11)
key varchar(32)
name varchar(50)
type varchar(1)
Here is my query:
select `key`, `id`, `name`, minus_month,month_cur
from `categories` as ct
left join (
select `category` as tr_ct_m, date_format(`dttm_trans`, '%Y%m') as dat, sum(`minus`) as minus_month, `minus_currency` as month_cur from `transactions` where dat = date_format(now(), '%Y%m')
) as tr_m on tr_m.tr_ct_m = ct.key
where `type` = '-'
I need to check clause in select before joining, because after sum of minus_month all dates are turning to Null.
Help plz
not sure if i understand you correctly,please try below:
select `ct`.`key`, `ct`.`id`, `ct`.`name`, tr_m.minus_month,tr_m.month_cur from
( select * from `categories` where `type` = '-') as ct
left join
( select `category` as tr_ct_m, date_format(`dttm_trans`, '%Y%m') as dat,
sum(`minus`) as minus_month, `minus_currency` as month_cur from `transactions`
where dat = date_format(now(), '%Y%m')
) as tr_m on tr_m.tr_ct_m = ct.key