Guest User

Untitled

a guest
Jan 17th, 2019
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.20 KB | None | 0 0
  1. CREATE TABLE transactions (
  2. id INT PRIMARY KEY AUTO_INCREMENT,
  3. code VARCHAR(10),
  4. date DATETIME,
  5. mode ENUM('Buy', 'Sell', 'Count', 'Return'),
  6. quantity INT,
  7. price DECIMAL(10,2),
  8. price_currency ENUM('ARS', 'USD'),
  9. usd_to_ars DECIMAL(10,2),
  10. return_id INT NULL DEFAULT NULL
  11. )
  12.  
  13. INSERT INTO transactions (code, date, mode, quantity, price, price_currency, usd_to_ars) VALUES ("a", "20180101", 'Buy', 4, 10, 'ARS', 3.7);
  14. INSERT INTO transactions (code, date, mode, quantity, price, price_currency, usd_to_ars) VALUES ("a", "20180102", 'Buy', 9, 8, 'ARS', 5.8);
  15. INSERT INTO transactions (code, date, mode, quantity, price, price_currency, usd_to_ars) VALUES ("a", "20180103", 'Sell', -3, 0, 'USD', 0);
  16. INSERT INTO transactions (code, date, mode, quantity, price, price_currency, usd_to_ars) VALUES ("b", "20180104", 'Buy', 5, 5, 'USD', 8.9);
  17. INSERT INTO transactions (code, date, mode, quantity, price, price_currency, usd_to_ars) VALUES ("a", "20180105", 'Buy', 2, 7, 'USD', 3.4);
  18. INSERT INTO transactions (code, date, mode, quantity, price, price_currency, usd_to_ars) VALUES ("b", "20180106", 'Buy', 1, 8, 'ARS', 9);
  19. INSERT INTO transactions (code, date, mode, quantity, price, price_currency, usd_to_ars) VALUES ("a", "20180107", 'Sell', -8, 0, 'USD', 4.4);
  20. INSERT INTO transactions (code, date, mode, quantity, price, price_currency, usd_to_ars) VALUES ("a", "20180108", 'Buy', 9, 9, 'ARS', 3.2);
  21. INSERT INTO transactions (code, date, mode, quantity, price, price_currency, usd_to_ars, return_id) VALUES ("a", "20180109", 'Return', 6, 2, 'ARS', 2, 2);
  22.  
  23. Select * FROM (SELECT
  24. id, date, code, mode, quantity, price, price_currency, usd_to_ars, return_id,
  25. @acm := @acm + quantity as stock,
  26. @avr := (@avr * (@acm - quantity) + if(quantity > 0, quantity * if(mode = "Return", @avr, if(price_currency = 'USD', price, price / usd_to_ars)), quantity * @avr)) / @acm as average_price_usd
  27. FROM
  28. transactions t1,
  29. (SELECT @acm := 0) x,
  30. (SELECT @avr := 0) y) t2
  31. ORDER BY id DESC
  32.  
  33. @avr := (@avr * (@acm - quantity) + if(quantity > 0, quantity * if(mode = "Return", @avr, if(price_currency = 'USD', price, price / usd_to_ars)), quantity * @avr)) / @acm as average_price_usd
  34.  
  35. If(mode = "Return", @avr, [...])
Add Comment
Please, Sign In to add comment