Advertisement
cdsatrian

running stock out

Apr 5th, 2017
168
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.32 KB | None | 0 0
  1. DROP TABLE IF EXISTS tabel;
  2. CREATE TABLE IF NOT EXISTS tabel(
  3.     id INT AUTO_INCREMENT PRIMARY KEY,
  4.     tgl DATE,
  5.     stok INT
  6. );
  7.  
  8. INSERT INTO tabel(tgl,stok)
  9. VALUES
  10. ('2012-08-01',50),
  11. ('2012-08-02',45),
  12. ('2012-08-03',40),
  13. ('2012-08-04',30);
  14.  
  15. SELECT * FROM tabel;
  16. +----+------------+------+
  17. | id | tgl        | stok |
  18. +----+------------+------+
  19. |  1 | 2012-08-01 |   50 |
  20. |  2 | 2012-08-02 |   45 |
  21. |  3 | 2012-08-03 |   40 |
  22. |  4 | 2012-08-04 |   30 |
  23. +----+------------+------+
  24.  
  25. SELECT d.id,d.tgl,d.stok,IFNULL(e.stok,d.stok)-d.stok AS keluar
  26. FROM
  27. (
  28. SELECT a.id AS id1, MAX(b.id) AS id2
  29. FROM
  30. tabel a
  31. LEFT JOIN tabel b ON b.id<a.id
  32. GROUP BY a.id
  33. ) c
  34. LEFT JOIN tabel d ON d.id=c.id1
  35. LEFT JOIN tabel e ON e.id=c.id2;
  36.  
  37. +------+------------+------+--------+
  38. | id   | tgl        | stok | keluar |
  39. +------+------------+------+--------+
  40. |    1 | 2012-08-01 |   50 |      0 |
  41. |    2 | 2012-08-02 |   45 |      5 |
  42. |    3 | 2012-08-03 |   40 |      5 |
  43. |    4 | 2012-08-04 |   30 |     10 |
  44. +------+------------+------+--------+
  45.  
  46. //--
  47. $sql="SELECT * FROM tabel";
  48. $result=$db->query($sql);
  49. $data=array();
  50. $i=-1;
  51. foreach($result as $row){
  52.     $data[++$i]=$row;
  53.     $data[$i]['keluar']=($i==0?0:$data[$i-1]['stok']);
  54.     echo "{$data[$i]['id']} | {$data[$i]['tgl']} | {$data[$i]['stok']} | {$data[$i]['keluar']}<br>";
  55. }
  56. //--
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement