Advertisement
kura2yamato

query point

Mar 14th, 2020
437
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
SQL 2.14 KB | None | 0 0
  1.  
  2. CREATE TABLE IF NOT EXISTS `tb_point` (
  3.   `id` INT(11) NOT NULL,
  4.   `user_id` INT(11) NOT NULL,
  5.   `created_at` DATE NOT NULL,
  6.   `points` INT(11) NOT NULL
  7. ) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=latin1;
  8.  
  9. --
  10. -- Dumping data for table `tb_point`
  11. --
  12.  
  13. INSERT INTO `tb_point` (`id`, `user_id`, `created_at`, `points`) VALUES
  14. (1, 1, '2020-01-15', 1),
  15. (2, 1, '2020-02-20', 3),
  16. (8, 1, '2020-03-14', 7),
  17. (9, 2, '2020-01-01', 3),
  18. (10, 2, '2020-02-15', 4),
  19. (11, 3, '2020-02-18', 2),
  20. (12, 3, '2020-03-01', 5);
  21.  
  22. -- --------------------------------------------------------
  23.  
  24. --
  25. -- Stand-in structure for view `v_user_join`
  26. --
  27. CREATE TABLE IF NOT EXISTS `v_user_join` (
  28. `user_id` INT(11)
  29. ,`tgl` DATE
  30. );
  31.  
  32. -- --------------------------------------------------------
  33.  
  34. --
  35. -- Structure for view `v_user_join`
  36. --
  37. DROP TABLE IF EXISTS `v_user_join`;
  38.  
  39. CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `v_user_join` AS SELECT `tb_point`.`user_id` AS `user_id`,MIN(`tb_point`.`created_at`) AS `tgl` FROM `tb_point` GROUP BY `tb_point`.`user_id`;
  40.  
  41. --
  42. -- Indexes for dumped tables
  43. --
  44.  
  45. --
  46. -- Indexes for table `tb_point`
  47. --
  48. ALTER TABLE `tb_point`
  49.   ADD PRIMARY KEY (`id`),
  50.   ADD KEY `user_id` (`user_id`);
  51.  
  52. --
  53. -- AUTO_INCREMENT for dumped tables
  54. --
  55.  
  56. --
  57. -- AUTO_INCREMENT for table `tb_point`
  58. --
  59. ALTER TABLE `tb_point`
  60.   MODIFY `id` INT(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=13;
  61.  
  62. --------------------
  63. SELECT p.user_id,MAX(p.points) points,MAX(created_at) tgl_max
  64. FROM `v_user_join` v_user
  65. JOIN tb_point p ON v_user.user_id =p.user_id
  66. WHERE tgl < '2020-02-01' AND p.created_at < '2020-02-01'
  67.  
  68. GROUP BY p.user_id
  69. -----
  70. SELECT p.user_id,MAX(p.points) points, date_format(created_at, "%Y-%m") tgl_show
  71. FROM `v_user_join` v_user
  72. JOIN tb_point p ON v_user.user_id =p.user_id
  73. WHERE tgl < '2020-02-01' AND p.created_at < '2020-02-01'
  74.  
  75. GROUP BY p.user_id
  76. -------------------
  77. SELECT SUM( MAX(p.points) )points, date_format(created_at, "%Y-%m") tgl_show
  78. FROM `v_user_join` v_user
  79. JOIN tb_point p ON v_user.user_id =p.user_id
  80. WHERE tgl < '2020-02-01' AND p.created_at < '2020-02-01'
  81. GROUP BY p.user_id
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement