I have a table called transactions which contains sellers and their transactions: sale, waste, and whenever they receive products. The structure is essentially as follows:
seller_id transaction_date quantity reason product unit_price
--------- ---------------- -------- ------ ------- ----------
1 2018-01-01 10 import 1 100.0
1 2018-01-01 -5 sale 1 100.0
1 2018-01-01 -1 waste 1 100.0
2 2018-01-01 -3 sale 4 95.5
I need a daily summary of each seller, including the value of their sales, waste and starting inventory. The problem is, the starting inventory is a cumulative sum of quantities up until the given day (the imports at the given day is also included). I have the following query:
SELECT
t.seller_id,
t.transaction_date,
t.SUM(quantity * unit_price) as amount,
t.reason as reason,
(
SELECT SUM(unit_price * quantity) FROM transactions
WHERE seller_id = t.seller_id
AND (transaction_date <= t.transaction_date)
AND (
transaction_date < t.transaction_date
OR reason = 'import'
)
) as opening_balance
FROM transactions t
GROUP BY
t.transaction_date,
t.seller_id
t.reason
The query works and I get the desired results. However, even after creating indices for both the outer and the subquery, it takes way too much time (about 30 seconds), because the opening_balance query is a dependant subquery which is calculated for each row over and over again.
How can i optimize, or rewrite this query?
Edit: the subquery had a small bug with a missing WHERE condition, i fixed it, but the essence of the question is the same. I created a fiddle with example data to play around:
https://www.db-fiddle.com/f/ma7MhufseHxEXLfxhCtGbZ/2
Following approach utilizing User-defined variables can be more performant than using the Correlated Subquery. In your case, a temp variable was used to account for the calculation logic, which also get outputted. You can ignore that.
You can try the following query (can add more explanation if needed):
Query
SELECT dt.reason,
dt.amount,
#bal := CASE
WHEN dt.reason = 'import'
AND #sid <> dt.seller_id THEN dt.amount
WHEN dt.reason = 'import' THEN #bal + #temp + dt.amount
WHEN #sid = 0
OR #sid = dt.seller_id THEN #bal
ELSE 0
end AS opening_balance,
#temp := CASE
WHEN dt.reason <> 'import'
AND #sid = dt.seller_id
AND #td = dt.transaction_date THEN #temp + dt.amount
ELSE 0
end AS temp,
#sid := dt.seller_id AS seller_id,
#td := dt.transaction_date AS transaction_date
FROM (SELECT seller_id,
transaction_date,
reason,
Sum(quantity * unit_price) AS amount
FROM transactions
WHERE seller_id IS NOT NULL
GROUP BY seller_id,
transaction_date,
reason
ORDER BY seller_id,
transaction_date,
Field(reason, 'import', 'sale', 'waste')) AS dt
CROSS JOIN (SELECT #sid := 0,
#td := '',
#bal := 0,
#temp := 0) AS user_vars;
Result (note that I have ordered by seller_id first and then transaction_date)
| reason | amount | opening_balance | temp | seller_id | transaction_date |
| ------ | ------ | --------------- | ----- | --------- | ---------------- |
| import | 1250 | 1250 | 0 | 1 | 2018-12-01 |
| sale | -850 | 1250 | -850 | 1 | 2018-12-01 |
| waste | -100 | 1250 | -950 | 1 | 2018-12-01 |
| import | 950 | 1250 | 0 | 1 | 2018-12-02 |
| sale | -650 | 1250 | -650 | 1 | 2018-12-02 |
| waste | -450 | 1250 | -1100 | 1 | 2018-12-02 |
| import | 2000 | 2000 | 0 | 2 | 2018-12-01 |
| sale | -1200 | 2000 | -1200 | 2 | 2018-12-01 |
| waste | -250 | 2000 | -1450 | 2 | 2018-12-01 |
| import | 750 | 1300 | 0 | 2 | 2018-12-02 |
| sale | -600 | 1300 | -600 | 2 | 2018-12-02 |
| waste | -450 | 1300 | -1050 | 2 | 2018-12-02 |
View on DB Fiddle
do thing something like this ?
SELECT s.* ,#balance:=#balance+(s.quantity*s.unit_price) AS opening_balance FROM (
SELECT t.* FROM transactions t
ORDER BY t.seller_id,t.transaction_date,t.reason
) s
CROSS JOIN ( SELECT #balance:=0) AS INIT
GROUP BY s.transaction_date, s.seller_id, s.reason;
SAMPLE
MariaDB [test]> select * from transactions;
+----+-----------+------------------+----------+------------+--------+
| id | seller_id | transaction_date | quantity | unit_price | reason |
+----+-----------+------------------+----------+------------+--------+
| 1 | 1 | 2018-01-01 | 10 | 100 | import |
| 2 | 1 | 2018-01-01 | -5 | 100 | sale |
| 3 | 1 | 2018-01-01 | -1 | 100 | waste |
| 4 | 2 | 2018-01-01 | -3 | 99.5 | sale |
+----+-----------+------------------+----------+------------+--------+
4 rows in set (0.000 sec)
MariaDB [test]> SELECT s.* ,#balance:=#balance+(s.quantity*s.unit_price) AS opening_balance FROM (
-> SELECT t.* FROM transactions t
-> ORDER BY t.seller_id,t.transaction_date,t.reason
-> ) s
-> CROSS JOIN ( SELECT #balance:=0) AS INIT
-> GROUP BY s.transaction_date, s.seller_id, s.reason;
+----+-----------+------------------+----------+------------+--------+-----------------+
| id | seller_id | transaction_date | quantity | unit_price | reason | opening_balance |
+----+-----------+------------------+----------+------------+--------+-----------------+
| 1 | 1 | 2018-01-01 | 10 | 100 | import | 1000 |
| 2 | 1 | 2018-01-01 | -5 | 100 | sale | 500 |
| 3 | 1 | 2018-01-01 | -1 | 100 | waste | 400 |
| 4 | 2 | 2018-01-01 | -3 | 99.5 | sale | 101.5 |
+----+-----------+------------------+----------+------------+--------+-----------------+
4 rows in set (0.001 sec)
MariaDB [test]>
SELECT
t.seller_id,
t.transaction_date,
SUM(quantity) as amount,
t.reason as reason,
quantityImport
FROM transaction t
inner join
(
select sum(ifnull(quantityImport,0)) quantityImport,p.transaction_date,p.seller_id from
( /* subquery get all the date and seller distinct row */
select transaction_date ,seller_id ,reason
from transaction
group by seller_id, transaction_date
)
as p
left join
( /* subquery get all the date and seller and the import quantity */
select sum(quantity) quantityImport,transaction_date ,seller_id
from transaction
where reason='Import'
group by seller_id, transaction_date
) as n
on
p.seller_id=n.seller_id
and
p.transaction_date>=n.transaction_date
group by
p.seller_id,p.transaction_date
) as q
where
t.seller_id=q.seller_id
and
t.transaction_date=q.transaction_date
GROUP BY
t.transaction_date,
t.seller_id,
t.reason;
Related
Consider I have the following rows in the table
| id | user_id | amount | date |
------------------------------------------------
| 1 | 1 | 100 | 2019-09-30 |
------------------------------------------------
| 2 | 2 | 100 | 2019-09-30 |
------------------------------------------------
| 3 | 1 | 100 | 2019-09-30 |
------------------------------------------------
| 4 | 3 | 100 | 2019-10-01 |
------------------------------------------------
| 5 | 1 | 75 | 2019-10-01 |
------------------------------------------------
| 6 | 3 | 100 | 2019-10-01 |
------------------------------------------------
| 7 | 1 | 35 | 2019-10-01 |
------------------------------------------------
I am trying find a way to get all the rows with user_id = 1 where the sum(amount) < 300 and date <= '2019-10-01'.
What I am trying to do is to only process records that meet a certain threshold sum. I am not quite sure where to start.
Expected Result
| id | user_id | amount | date |
------------------------------------------------
| 1 | 1 | 100 | 2019-09-30 |
------------------------------------------------
| 3 | 1 | 100 | 2019-09-30 |
------------------------------------------------
| 5 | 1 | 75 | 2019-10-01 |
------------------------------------------------
Here is what I have tried so far
SELECT id, SUM(amount) as total_sum
FROM table
WHERE date <= '2019-10-01' AND user_id = 1
ORDER BY date ASC
HAVING total_sum <= 300
I don't get the desired output based on the above query.
MySQL Version currently using: 5.7.25
I did look at this question MySQL select records with sum greater than threshold assuming they are trying to do the same thing, but this isn't what I am looking at
It is a Rolling Sum problem. In MySQL 8.0.2 and above, you can solve this using Window functions with Frames. In older versions, we can do the same using User-defined Session variables.
We first calculate the rolling sum using Session variables.
Then, use the result-set in a Derived table, and find the id where total sum crosses the "barrier" of 300. Barrier is reached when the New rolling Sum is greater than 300. We set the barrier value to 1 at this point, 0 for rows before it, and 2 and more, for the rows afterwards.
We will only consider the rows where barrier is 0.
Try (works for all MySQL versions):
Query #1
SELECT dt.id,
dt.user_id,
dt.amount,
dt.date
FROM
(
SELECT
t.id,
t.user_id,
t.amount,
t.date,
#barrier := CASE
WHEN
(#tot_qty := #tot_qty + t.amount) > 300
THEN (#barrier + 1)
ELSE 0
END AS barrier
FROM
your_table AS t
CROSS JOIN (SELECT #tot_qty := 0,
#barrier := 0) AS user_init
WHERE t.user_id = 1
AND t.date <= '2019-10-01'
ORDER BY t.user_id, t.date, t.id
) AS dt
WHERE dt.barrier = 0
ORDER BY dt.user_id, dt.date, dt.id;
Result
| id | user_id | amount | date |
| --- | ------- | ------ | ---------- |
| 1 | 1 | 100 | 2019-09-30 |
| 3 | 1 | 100 | 2019-09-30 |
| 5 | 1 | 75 | 2019-10-01 |
View on DB Fiddle
If you don't like to use Session Variables (some experienced SO users dislike them vehemently), you can utilize a technique based on "Self-Join" and then use GROUP BY with HAVING to filter out.
General idea is that we left join to get previous rows for the specific user_id, and then aggregate to get the rolling sum, and then filtering using Having clause.
Query
SELECT
t1.*
FROM
your_table AS t1
LEFT JOIN your_table AS t2
ON t2.user_id = t1.user_id
AND t2.date <= t1.date
AND t2.id <= t1.id
WHERE t1.user_id = 1
AND t1.date <= '2019-10-31'
GROUP BY t1.user_id, t1.date, t1.id, t1.amount
HAVING COALESCE(SUM(t2.amount),0) < 300;
Result
| id | user_id | amount | date |
| --- | ------- | ------ | ---------- |
| 1 | 1 | 100 | 2019-09-30 |
| 3 | 1 | 100 | 2019-09-30 |
| 5 | 1 | 75 | 2019-10-01 |
View on DB Fiddle
You can benchmark both the approaches and decide which one is suitable.
For this query, you will need the composite index: (user_id, date)
I have 3 tables in my database. Here how it looks:
tbl_production:
+--------+------------+-----+-------+
| id_pro | date | qty | stock |
+--------+------------+-----+-------+
| 1 | 2017-09-09 | 100 | 93 |
| 2 | 2017-09-10 | 100 | 100 |
tbl_out:
+--------+------------+-----+
| id_out | date | qty |
+--------+------------+-----+
| 1 | 2017-09-09 | 50 |
| 2 | 2017-09-09 | 50 |
| 3 | 2017-09-10 | 50 |
| 4 | 2017-09-10 | 50 |
tbl_return:
+--------+------------+-----+
| id_out | date | qty |
+--------+------------+-----+
| 1 | 2017-09-09 | 48 |
| 2 | 2017-09-09 | 50 |
| 3 | 2017-09-10 | 60 |
| 4 | 2017-09-10 | 35 |
I would like to get the result the stock of the day. This what the table should be:
+------------+------+
| date | sotd |
+------------+------+
| 2017-09-09 | 98 |
| 2017-09-09 | 193 |
This result is from the
accumulated stock from the days before + tbl_production.qty -
SUM(tbl_out.qty) GROUP by date + SUM(tbl_return.qty) GROUP by date
The stock of the date from 2017-09-09 is from 0 (because this is the first production) + 100 - 100 + 98 = 98
The stock of the date from 2017-09-10 is from 98 (accumulated stock from the days before) + 100 - 100 + 95 = 193
I already have the query something like this, but it can't be executed
SET #running_count := 0;
SELECT *,
#running_count := #running_count + qty - (SELECT SUM(qty) FROM tbl_out GROUP BY date) + (SELECT SUM(qty) FROM tbl_return GROUP BY date) AS Counter
FROM tbl_production
ORDER BY id_prod;
How can I get this result?
In MySQL, GROUP BY and variables don't always work well together. Try:
SELECT p.date,
(#qty := #qty + qty) as running_qty
FROM (SELECT p.date, SUM(qty) as qty
FROM tbl_production p
GROUP BY p.date
) p CROSS JOIN
(SELECT #qty := 0) params
ORDER BY p.date;
EDIT:
If you want the value from the day before, the expression is a bit complicated, but not hard:
SELECT p.date,
(CASE WHEN (#save_qty := #qty) = NULL THEN -1 -- never happens
WHEN (#qty := #qty + qty) = NULL THEN -1 -- never happens
ELSE #save_qty
END) as start_of_day
FROM (SELECT p.date, SUM(qty) as qty
FROM tbl_production p
GROUP BY p.date
) p CROSS JOIN
(SELECT #qty := 0) params
ORDER BY p.date;
I have a Transaction table that records every amount added to or subtracted from the balance of a Customer, with the new balance:
+----+------------+------------+--------+---------+
| id | customerId | timestamp | amount | balance |
+----+------------+------------+--------+---------+
| 1 | 1 | 1000000001 | 10 | 10 |
| 2 | 1 | 1000000002 | -20 | -10 |
| 3 | 1 | 1000000003 | -10 | -20 |
| 4 | 2 | 1000000004 | -5 | -5 |
| 5 | 2 | 1000000005 | -5 | -10 |
| 6 | 2 | 1000000006 | 10 | 0 |
| 7 | 3 | 1000000007 | -5 | -5 |
| 8 | 3 | 1000000008 | 10 | 5 |
| 9 | 3 | 1000000009 | 10 | 15 |
| 10 | 4 | 1000000010 | 5 | 5 |
+----+------------+------------+--------+---------+
The Customer table stores the current balance, and looks like:
+----+---------+
| id | balance |
+----+---------+
| 1 | -20 |
| 2 | 0 |
| 3 | 15 |
| 4 | 5 |
+----+---------+
I would like to add a balanceSignSince column, that would store the timestamp at which the balance sign last changed. Transitioning to and from positive, negative, or zero counts as a balance change.
After the update, based on the above data, the Customer table should contain:
+----+---------+------------------+
| id | balance | balanceSignSince |
+----+---------+------------------+
| 1 | -20 | 1000000002 |
| 2 | 0 | 1000000006 |
| 3 | 15 | 1000000008 |
| 4 | 5 | 1000000010 |
+----+---------+------------------+
How can I write a SQL query that updates every Customer with the last time the balance sign changed, based on the Transaction table?
I suspect I can't do this without a quite complex stored procedure, but am curious to see if any clever ideas come up.
This uses a simulated rank() function.
select customerId, min(tstamp) from
(
select tstamp,
if (#cust = customerId and sign(#bal) = sign(balance), #rn := #rn,
if (#cust = customerId and sign(#bal) <> sign(balance), #rn := #rn + 1, #rn := 0)) as rn,
#cust := customerId as customerId, #bal := balance as balance
from
(select #rn := 0) x,
(select id, #cust := customerId as customerId, tstamp, amount, #bal := balance as balance
from trans order by customerId, tstamp desc) y
) z
where rn = 0
group by customerId;
Check it: http://rextester.com/XJVKK61181
This script returns a table like this:
+------------+----+------------+---------+
| tstamp | rn | customerId | balance |
+------------+----+------------+---------+
| 1000000003 | 0 | 1 | -20 |
| 1000000002 | 0 | 1 | -10 |
| 1000000001 | 1 | 1 | 10 |
| 1000000006 | 0 | 2 | 0 |
| 1000000005 | 2 | 2 | -10 |
| 1000000004 | 2 | 2 | -5 |
| 1000000009 | 0 | 3 | 15 |
| 1000000008 | 2 | 3 | 5 |
| 1000000007 | 3 | 3 | -5 |
| 1000000010 | 0 | 4 | 5 |
+------------+----+------------+---------+
Then selecting min(timestamp) of files where rn = 0:
+------------+-------------+
| customerId | min(tstamp) |
+------------+-------------+
| 1 | 1000000002 |
+------------+-------------+
| 2 | 1000000006 |
+------------+-------------+
| 3 | 1000000009 |
+------------+-------------+
| 4 | 1000000010 |
+------------+-------------+
Updated answer with the restriction that this needs to work on the existing data
The following query should work for most cases, there is still an issue with customers having only a single transaction or no sign change. As this is a one time update, I would run the query below and then do a simple update for all users not having a timestamp set, for them it's going to be the timestamp of the first transaction:
# Find the smallest timestamp, e.g. the
# transaction which changed the signum.
SELECT
p.customerId as customerId,
MIN(t.timestamp) as balanceSignSince
FROM
transaction as t,
(
# find the latest timestamp having
# a different sign for each user.
# Here is the issue with users having
# only a single transaction or no sign
# changes.
SELECT
u.customerId as customerId,
MAX(t.timestamp) as balanceSignSince
FROM
transaction as t,
customer as c,
(
# find the timestamp of the very last
# transaction for every user.
SELECT
t.customerId as customerId,
MAX(t.timestamp) as lastTransaction
FROM
transaction as t
GROUP BY
t.customerId
) as u
WHERE
u.customerId = c.id
AND u.customerId = t.customerId
AND SIGN(c.balance) <> SIGN(t.balance)
GROUP BY
u.customerId
) as p
WHERE
p.customerId = t.customerId
AND p.balanceSignSince < t.timestamp
GROUP BY
p.customerId;
Fiddle: http://sqlfiddle.com/#!9/bd0760/13
Original Answer
This should work to get the timestamp of a sign change:
SELECT
c.id as id,
MAX(t.timestamp) as balanceSignSince
FROM
transaction as t,
customer as c
WHERE
t.customerId = c.id
AND SIGN(t.balance) <> SIGN(c.balance)
This needs to be executed before the customer table is updated with the new balance. If you have a trigger on transation:insert you should probably put the above into the query updating the customer table.
I am working with a dataset with a similar format to the following:
Table: Account
*-----------*----------*-------------*
| id | amount | date |
*-----------*----------*-------------*
| 1 | 100 | 01/01/2016 |
| 2 | 100 | 01/02/2016 |
| 3 | 100 | 01/03/2016 |
| 4 | 200 | 01/04/2016 |
| 5 | 200 | 01/05/2016 |
| 6 | 200 | 01/06/2016 |
| 7 | 300 | 01/07/2016 |
| 8 | 300 | 01/08/2016 |
| 9 | 300 | 01/09/2016 |
| 10 | 400 | 01/10/2016 |
*-----------*----------*-------------*
I need a query to return that returns the most recent record for every distinct value in the table. So, the above table would return
*-----------*----------*-------------*
| id | amount | date |
*-----------*----------*-------------*
| 3 | 100 | 01/03/2016 |
| 6 | 200 | 01/06/2016 |
| 9 | 300 | 01/09/2016 |
| 10 | 400 | 01/10/2016 |
*-----------*----------*-------------*
I am still new to subqueries but I tried the following
SELECT a.id, a.amount, a.date FROM account a WHERE a.date IN (SELECT MAX(date) FROM account)
However this only return the latest date. How can I get the latest date for every distinct value in the amount column.
If you only need amount:
SELECT amount, MAX(date) from myTable group by amount
If you need more data:
SELECT * from myTable where (amount, date) IN (
SELECT amount, MAX(date) as date from table group by amount
)
Or maybe this will run faster:
SELECT * from myTable A WHERE NOT EXISTS (
SELECT 1
FROM myTable B
WHERE A.date < B.date
AND A.amount = B.amount
)
I have two tables, one with the main data and a second table with historical values.
Table stocks
+----------+-------+-----------+
| stock_id | symbol| name |
+----------+-------+-----------+
| 1 | AAPL | Apple |
| 2 | GOOG | Google |
| 3 | MSFT | Microsoft |
+----------+-------+-----------+
Table prices
+----------+-------+---------------------+
| stock_id | price | date |
+----------+-------+---------------------+
| 1 | 0.05 | 2015-02-24 01:00:00 |
| 2 | 2.20 | 2015-02-24 01:00:00 |
| 1 | 0.50 | 2015-02-23 23:00:00 |
| 2 | 1.90 | 2015-02-23 23:00:00 |
| 3 | 2.10 | 2015-02-23 23:00:00 |
| 1 | 1.00 | 2015-02-23 19:00:00 |
| 2 | 1.00 | 2015-02-23 19:00:00 |
+----------+-------+---------------------+
I need a query that returns:
+----------+-------+-----------+-------+
| stock_id | symbol| name | diff |
+----------+-------+-----------+-------+
| 1 | AAPL | Apple | -0.45 |
| 2 | GOOG | Google | 0.30 |
| 3 | MSFT | Microsoft | NULL |
+----------+-------+-----------+-------+
Where diff is the result of subtracting from the newest price of a stock the previous price.
If one or less prices are present for a particular stock I should get NULL.
I have the following queries that return the last price and the previous price but I don't know how to join everything
/* last */
SELECT price
FROM prices
WHERE stock_id = '1'
ORDER BY date DESC
LIMIT 1
/* previous */
SELECT price
FROM prices
WHERE stock_id = '1'
ORDER BY date DESC
LIMIT 1,1
Using MySQL 5.5
This will return the expected result set:
SELECT stock_id, symbol, name,
SUM(CASE WHEN row_number = 1 THEN price END) -
SUM(CASE WHEN row_number = 2 THEN price END) AS diff
FROM (
SELECT #row_number:=CASE WHEN #stock=stock_id THEN #row_number+1
ELSE 1
END AS row_number,
#stock:=stock_id AS stock_id,
price, date, symbol, name
FROM (SELECT p.stock_id, s.symbol, s.name, p.price, p.date
FROM prices AS p
INNER JOIN stocks AS s ON p.stock_id = s.stock_id
ORDER BY stock_id, date DESC) AS t
) u
GROUP BY u.stock_id
SQL Fiddle Demo
This should do it:
SELECT s1.symbol,
s1.name,
COALESCE ((SELECT price
FROM prices p1
WHERE p1.stock_id = s1.stock_id
ORDER BY dateTime DESC
LIMIT 1), 0) -
COALESCE ((SELECT price
FROM prices p2
WHERE p2.stock_id = s1.stock_id
ORDER BY dateTime DESC
LIMIT 1,1), 0) AS diff
FROM stocks s1;