Income and Expense calculation - mysql

I need to show income and expense per day
Income and expenses are different table
I need to show in following format, for ex:
17/08/2019 date have two incomes in the table
I need to calculate sum of the income in the date, showing on the result with the same day expense.
I have tried with some queries, but it's not working.
Date | Income | Expense | Profit
Select SUM(d.amount)
, SUM(e.amount)
, d.date
, e.date
FROM due d
JOIN expenses e
ON d.date = e.date
Expense table -table-name : expenses
id | date | details | amount
1 13-08-2019 daily 50
2 17-08-2019 cleaning 50
3 17-08-2019 cleaning 50
4 18-08-2019 Tea 150
5 18-08-2019 other 50
Income table -table-name : due
id | date | amount
4 12-08-2019 150
5 13-08-2019 100
6 18-08-2019 450
7 18-08-2019 50
result will be:
id | date | Income | Expense | Profit
1 12-08-2019 150 NULL 150
2 13-08-2019 100 50 50
3 17-08-2019 NULL 100 -100
4 18-08-2019 500 200 300

In the future, I'd suggest posting some table details by using SHOW CREATE TABLE table_name which will allow us to better assist you.
You should be able to use a union and some grouping to get what you are after:
SELECT
Date,
SUM(Income) as Income,
SUM(Expense) as Expense,
SUM(Income) - SUM(Expense) as Profit
FROM (
SELECT
due.date as Date,
due.amount as Income,
0 as Expense
FROM due
UNION ALL
SELECT
expenses.date as Date
0 as Income,
expenses.amount as Expense
FROM expenses
)
GROUP BY Date

Related

MySQL SUM two columns then another column with the net amount

Hi ive tried all the solution on stack over flow to no avail
i have 2 tables with a ID primary key, then date, and amount. there can be multiple dates of the same date in the table. the debits uses negative numbers in debits table
table "credits"
id | date | amount
1 2020-01-01 10.00
2 2020-01-02 20.00
3 2020-01-03 30.00
4 2020-01-01 10.00
5 2020-01-02 10.00
6 2020-01-03 10.00
table "debits"
id | date | amount
55 2020-01-01 -5.00
56 2020-01-02 -5.00
57 2020-01-03 -5.00
58 2020-01-01 -5.00
59 2020-01-02 -5.00
60 2020-01-03 -5.00
I want to return a 3 column result like so, grouped by DATE with 4 fields, date, amount credits (for teh day) amount debits (for the day) and the amont total (for the day)
date | amount_credits | amount_debits | amount_total
2020-01-01 20 10 10
2020-01-02 30 10 20
2020-01-03 40 10 30
I would do this using union all and aggrgtion:
select date, sum(credit) as credits, abs(sum(debits)) as debits),
sum(credits) + sum(debits) as net
from ((select c.date, c.amount as credit, 0 as debit
from credits c
) union all
(select c.date, 0, d.amount
from debits d
)
) cd
group by date;
I note that the sign of the debits amount changes, from the source table to the result set, which is why the outer query uses abs().
In particular, using union all and group by ensures that all dates in the original data are in the result set -- even if the date in in only one of the tables.
I'd group both tables on the date and then join the two:
SELECT c.date, amount_credits, amount_debits, amount_credits - amount_debits AS amount_total
FROM (SELECT date, SUM(amount) AS amount_credits
FROM credits
GROUP BY date) c
JOIN (SELECT date, -1 * SUM(amount) AS amount_debits
FROM debits
GROUP BY date) d ON c.date = d.date

Getting wrong data from DB when joining MySql [duplicate]

I have a table of revenue as
title_id revenue cost
1 10 5
2 10 5
3 10 5
4 10 5
1 20 6
2 20 6
3 20 6
4 20 6
when i execute this query
SELECT SUM(revenue),SUM(cost)
FROM revenue
GROUP BY revenue.title_id
it produces result
title_id revenue cost
1 30 11
2 30 11
3 30 11
4 30 11
which is ok, now i want to combine sum result with another table which has structure like this
title_id interest
1 10
2 10
3 10
4 10
1 20
2 20
3 20
4 20
when i execute join with aggregate function like this
SELECT SUM(revenue),SUM(cost),SUM(interest)
FROM revenue
LEFT JOIN fund ON revenue.title_id = fund.title_id
GROUP BY revenue.title_id,fund.title_id
it double the result
title_id revenue cost interest
1 60 22 60
2 60 22 60
3 60 22 60
4 60 22 60
I can't understand why is it double it,please help
Its doubling because you have title repeated in fund and revenue tables. This multiplies the number of records where it matches. This is pretty easy to see if you remove the aggregate functions and look at the raw data. See here
The way to get around this is to create inline views of your aggregates and join on the those results.
SELECT R.title_id,
R.revenue,
R.cost,
F.interest
FROM (SELECT title_id,
Sum(revenue) revenue,
Sum(cost) cost
FROM revenue
GROUP BY revenue.title_id) r
LEFT JOIN (SELECT title_id,
Sum(interest) interest
FROM fund
GROUP BY title_id) f
ON r.title_id = F.title_id
output
| TITLE_ID | REVENUE | COST | INTEREST |
----------------------------------------
| 1 | 30 | 11 | 30 |
| 2 | 30 | 11 | 30 |
| 3 | 30 | 11 | 30 |
| 4 | 30 | 11 | 30 |
demo
The reason for this is that you have joined the table the first derived table from the second table without grouping it. To solve the problem, group the second table (fund) and join it with the first derived table using LEFT JOIN.
SELECT b.title_id,
b.TotalRevenue,
b.TotalCost,
d.TotalInterest
FROM
(
SELECT a.title_id,
SUM(a.revenue) TotalRevenue,
SUM(a.cost) TotalCost
FROM revenue a
GROUP BY a.title_id
) b LEFT JOIN
(
SELECT c.title_id,
SUM(a.interest) TotalInterest
FROM fund c
GROUP BY c.title_id
) d ON b.title_id = d.title_id
There are two rows for each title_id in revenue table.

Conditional Window Functions

I have a sales table that looks like this:
store_id cust_id txn_id txn_date amt industry
200 1 1 20180101 21.01 1000
200 2 2 20200102 20.01 1000
200 2 3 20200103 19 1000
200 3 4 20180103 19 1000
200 4 5 20200103 21.01 1000
300 2 6 20200104 1.39 2000
300 1 7 20200105 12.24 2000
300 1 8 20200105 25.02 2000
400 2 9 20180106 103.1 1000
400 2 10 20200107 21.3 1000
Here's the code to generate this sample table:
CREATE TABLE sales(
store_id INT,
cust_id INT,
txn_id INT,
txn_date bigint,
amt float,
industry INT);
INSERT INTO sales VALUES(200,1,1,20180101,21.01,1000);
INSERT INTO sales VALUES(200,2,2,20200102,20.01,1000);
INSERT INTO sales VALUES(200,2,3,20200103,19.00,1000);
INSERT INTO sales VALUES(200,3,4,20180103,19.00,1000);
INSERT INTO sales VALUES(200,4,5,20200103,21.01,1000);
INSERT INTO sales VALUES(300,2,6,20200104,1.39,2000);
INSERT INTO sales VALUES(300,1,7,20200105,12.24,2000);
INSERT INTO sales VALUES(300,1,8,20200105,25.02,2000);
INSERT INTO sales VALUES(400,2,9,20180106,103.1,1000);
INSERT INTO sales VALUES(400,2,10,20200107,21.3,1000);
What I would like to do is create a new table, results that answers the question: what percentage of my VIP customers have, since January 3rd 2020, shopped i) at my store only; ii) at my store and at other stores in the same industry; iii) at only other stores in the same industry? Define a VIP customer to be someone who has shopped at a given store at least once since 2019.
Here's the target output table:
store industry pct_my_store_only pct_both pct_other_stores_only
200 1000 0.5 0.5 0.0
300 2000 0.5 0.5 0.0
400 1000 0.0 1.0 0.0
I'm trying to use window functions to accomplish this. Here's what I have so far:
CREATE TABLE results as
SELECT s.store_id, s.industry,
COUNT(DISTINCT (CASE WHEN s.txn_date>=20200103 THEN s.cust_id END)) * 1.0 / sum(count(DISTINCT (CASE WHEN s.txn_date>=20200103 THEN s.cust_id END))) OVER (PARTITION BY s.industry) AS pct_my_store_only
...AS pct_both
...AS pct_other_stores_only
FROM sales s
WHERE sales.txn_date>=20190101
GROUP BY s.store_id, s.industry;
The above does not seem to be correct; how can I correct this?
Join the distinct store_ids and industries to the concatenated distinct store_ids and industries for each customer and then use window function avg() with the function find_in_set() to determine if a customer how many customer have shopped or not from each store:
with
stores as (
select distinct store_id, industry
from sales
where txn_date >= 20190103
),
customers as (
select cust_id,
group_concat(distinct store_id) stores,
group_concat(distinct industry) industries
from sales
where txn_date >= 20190103
group by cust_id
),
cte as (
select *,
avg(concat(s.store_id) = concat(c.stores)) over (partition by s.store_id, s.industry) pct_my_store_only,
avg(find_in_set(s.store_id, c.stores) = 0) over (partition by s.industry) pct_other_stores_only
from stores s inner join customers c
on find_in_set(s.industry, c.industries) and find_in_set(s.store_id, c.stores)
)
select distinct store_id, industry,
pct_my_store_only,
1 - pct_my_store_only - pct_other_stores_only pct_both,
pct_other_stores_only
from cte
order by store_id, industry
See the demo.
Results:
> store_id | industry | pct_my_store_only | pct_both | pct_other_stores_only
> -------: | -------: | ----------------: | -------: | --------------------:
> 200 | 1000 | 0.5000 | 0.5000 | 0.0000
> 300 | 2000 | 0.5000 | 0.5000 | 0.0000
> 400 | 1000 | 0.0000 | 1.0000 | 0.0000

Single query to retrieve multiple values from multiple tables

Expenses table
1/1/2016 exp1 2000
13/1/2016 exp11 2500
1/2/2016 exp2 1500
1/3/2016 exp3 1000
10/3/2016 exp1 2000
Income table
1/1/2016 income1 2500
1/2/2016 income2 3500
1/3/2016 income3 1500
10/3/2016 income3 1000
1/4/2016 income4 5000
From single query what I need is group by month, this is what I need
Expenses Incomes Month
4500 2500 Jan
1500 3500 Feb
3000 2500 Mar
0 5000 April
I need the above query to show the data in Google graph
Terrible data structure and format, but not impossible:
SELECT
IFNULL(exp.Expenses,0) Expenses,
IFNULL(inc.Incomes,0) Incomes,
inc.`monthname` `Month`
FROM
(
SELECT
SUM(i.amount) Incomes,
MONTHNAME(STR_TO_DATE(i.`date`, '%d/%m/%Y')) `monthname`,
MONTH(STR_TO_DATE(i.`date`, '%d/%m/%Y')) `month`
FROM
incomes i
GROUP BY
MONTHNAME(STR_TO_DATE(i.`date`, '%d/%m/%Y')),
MONTH(STR_TO_DATE(i.`date`, '%d/%m/%Y'))
) inc
LEFT JOIN
(
SELECT
SUM(e.amount) Expenses,
MONTHNAME(STR_TO_DATE(e.`date`, '%d/%m/%Y')) `monthname`,
MONTH(STR_TO_DATE(e.`date`, '%d/%m/%Y')) `month`
FROM
expenses e
GROUP BY
MONTHNAME(STR_TO_DATE(e.`date`, '%d/%m/%Y')),
MONTH(STR_TO_DATE(e.`date`, '%d/%m/%Y'))
) exp
ON exp.`month` = inc.`month`
ORDER BY
inc.`month`
Output of this simplicity:
+----------+---------+----------+
| Expenses | Incomes | Month |
+----------+---------+----------+
| 4500 | 2500 | January |
| 1500 | 3500 | February |
| 3000 | 2500 | March |
| 0 | 5000 | April |
+----------+---------+----------+
4 rows in set
Anyway better thing seriously how to improve and normalize your data.
In my solution, I give the number of the month rather than text. I'll leave it to you to convert it to text (using a CASE expression, for example) if you wish:
SELECT
sum(expense) AS total_expense, sum(income) AS total_income, trans_month
FROM (
SELECT
month(trans_date) AS trans_month,
0 AS income,
sum(amount) AS expense
FROM expense
GROUP BY month(trans_date)
UNION ALL
SELECT
month(trans_date) AS trans_month,
sum(amount) AS income,
0 AS expense
FROM income
GROUP BY month(trans_date)
) AS a
GROUP BY trans_month;

Mysql join and sum is doubling result

I have a table of revenue as
title_id revenue cost
1 10 5
2 10 5
3 10 5
4 10 5
1 20 6
2 20 6
3 20 6
4 20 6
when i execute this query
SELECT SUM(revenue),SUM(cost)
FROM revenue
GROUP BY revenue.title_id
it produces result
title_id revenue cost
1 30 11
2 30 11
3 30 11
4 30 11
which is ok, now i want to combine sum result with another table which has structure like this
title_id interest
1 10
2 10
3 10
4 10
1 20
2 20
3 20
4 20
when i execute join with aggregate function like this
SELECT SUM(revenue),SUM(cost),SUM(interest)
FROM revenue
LEFT JOIN fund ON revenue.title_id = fund.title_id
GROUP BY revenue.title_id,fund.title_id
it double the result
title_id revenue cost interest
1 60 22 60
2 60 22 60
3 60 22 60
4 60 22 60
I can't understand why is it double it,please help
Its doubling because you have title repeated in fund and revenue tables. This multiplies the number of records where it matches. This is pretty easy to see if you remove the aggregate functions and look at the raw data. See here
The way to get around this is to create inline views of your aggregates and join on the those results.
SELECT R.title_id,
R.revenue,
R.cost,
F.interest
FROM (SELECT title_id,
Sum(revenue) revenue,
Sum(cost) cost
FROM revenue
GROUP BY revenue.title_id) r
LEFT JOIN (SELECT title_id,
Sum(interest) interest
FROM fund
GROUP BY title_id) f
ON r.title_id = F.title_id
output
| TITLE_ID | REVENUE | COST | INTEREST |
----------------------------------------
| 1 | 30 | 11 | 30 |
| 2 | 30 | 11 | 30 |
| 3 | 30 | 11 | 30 |
| 4 | 30 | 11 | 30 |
demo
The reason for this is that you have joined the table the first derived table from the second table without grouping it. To solve the problem, group the second table (fund) and join it with the first derived table using LEFT JOIN.
SELECT b.title_id,
b.TotalRevenue,
b.TotalCost,
d.TotalInterest
FROM
(
SELECT a.title_id,
SUM(a.revenue) TotalRevenue,
SUM(a.cost) TotalCost
FROM revenue a
GROUP BY a.title_id
) b LEFT JOIN
(
SELECT c.title_id,
SUM(a.interest) TotalInterest
FROM fund c
GROUP BY c.title_id
) d ON b.title_id = d.title_id
There are two rows for each title_id in revenue table.