Advertisement
cdsatrian

range quantity 20170318

Mar 18th, 2017
160
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
MySQL 1.21 KB | None | 0 0
  1. DROP TABLE IF EXISTS tbl_products;
  2. CREATE TABLE IF NOT EXISTS tbl_products(
  3.     id INT PRIMARY KEY,
  4.     quantity INT
  5. );
  6. INSERT INTO tbl_products
  7. VALUES
  8. (1,250),
  9. (2,100),
  10. (3,200),
  11. (4,150),
  12. (5,210);
  13.  
  14. SELECT * FROM tbl_products;
  15.  
  16. +----+----------+
  17. | id | quantity |
  18. +----+----------+
  19. |  1 |      250 |
  20. |  2 |      100 |
  21. |  3 |      200 |
  22. |  4 |      150 |
  23. |  5 |      210 |
  24. +----+----------+
  25.  
  26. //-- membuat range id tiap product
  27. SELECT
  28.     a.*, (SUM(b.quantity)-a.quantity+1) AS awal,SUM(b.quantity) AS akhir
  29. FROM
  30.     tbl_products a
  31.     JOIN tbl_products b ON b.id<=a.id
  32. GROUP
  33.     BY a.id;
  34.  
  35. +----+----------+------+-------+
  36. | id | quantity | awal | akhir |
  37. +----+----------+------+-------+
  38. |  1 |      250 |    1 |   250 |
  39. |  2 |      100 |  251 |   350 |
  40. |  3 |      200 |  351 |   550 |
  41. |  4 |      150 |  551 |   700 |
  42. |  5 |      210 |  701 |   910 |
  43. +----+----------+------+-------+
  44.  
  45. //-- mencari id product pada posisi 401
  46. SELECT
  47.     c.id
  48. FROM
  49.     (
  50.     SELECT
  51.         a.*, (SUM(b.quantity)-a.quantity+1) AS awal,SUM(b.quantity) AS akhir
  52.     FROM
  53.         tbl_products a
  54.         JOIN tbl_products b ON b.id<=a.id
  55.     GROUP BY
  56.         a.id
  57.     ) c
  58. WHERE
  59.     401 BETWEEN c.awal AND c.akhir;
  60.    
  61. +----+
  62. | id |
  63. +----+
  64. |  3 |
  65. +----+
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement