php mysql在记录之间按月选择

时间:2018-05-24 15:44:40

标签: php mysql

我有这个MySQL表my_table:

+-------+------------+-----------+
|Student|    Date    | Classroom |
+-------+------------+-----------+
|     1 | 2018-01-01 |       101 |
|     2 | 2018-01-01 |       102 |
|     3 | 2018-01-01 |       103 |
|     1 | 2018-03-01 |       104 |
|     2 | 2018-06-01 |       103 |
|     3 | 2018-09-01 |       104 |
|     1 | 2018-11-01 |       106 |
|     2 | 2018-12-01 |       101 |
+-------+------------+-----------+

学生们留在指定的教室直到改变。

我正试图让他们在哪个教室待一个月。

例如10月(10),学生1在104,2在103,3在104.

我真的不确定如何继续这个,所以感谢任何帮助。

目前使用此查询基于草莓答案

SELECT x.* 
FROM my_table x 
LEFT OUTER JOIN my_table y 
ON y.student = x.student
AND y.date < x.date
WHERE x.date <= LAST_DAY('2018-10-01')
GROUP BY student

3 个答案:

答案 0 :(得分:0)

DROP TABLE IF EXISTS my_table;

CREATE TABLE my_table
(Student INT NOT NULL, Date DATE NOT NULL, Classroom INT NOT NULL,PRIMARY KEY(student,classroom));

INSERT INTO my_table VALUES
(1,'2018-01-01',101),
(2,'2018-01-01',102),
(3,'2018-01-01',103),
(1,'2018-03-01',104),
(2,'2018-06-01',103),
(3,'2018-09-01',104),
(1,'2018-11-01',106),
(2,'2018-12-01',101);

SELECT x.* 
  FROM my_table x 
  JOIN 
     ( SELECT student
            , MAX(date) date 
         FROM my_table 
        WHERE date <= LAST_DAY('2018-10-01') 
        GROUP 
           BY student
     ) y 
    ON y.student = x.student 
   AND y.date = x.date;

+---------+------------+-----------+
| Student | Date       | Classroom |
+---------+------------+-----------+
|       1 | 2018-03-01 |       104 |
|       2 | 2018-06-01 |       103 |
|       3 | 2018-09-01 |       104 |
+---------+------------+-----------+

答案 1 :(得分:0)

这里有一个(在存储过程中使用的代码段;假设表格为example&amp; output to table months)。它为每个学生每个月产生一排。

drop table months;
create table months (month date, student integer, classroom integer);
set @month = (select min(date) from example);
start_loop: LOOP
    insert into months select @month, s1.student, classroom from
    (select student, max(date) as maxdate from example where date <= @month group by student) s1
    join example s2 on s1.student = s2.student and maxdate = date;
    if @month = (select max(date) from example) then
        leave start_loop;
    end if;
    set @month = @month + interval 1 month;
END LOOP start_loop;

答案 2 :(得分:-1)

让我们将问题分成两部分。首先,查找到目前为止已分配给学生A的所有房间,并使用日期对它们进行排序。接下来,找到恰好在所需月份之前或之前的记录。

例如:

考虑学生1.我们得到

+-------+------------+-----------+
|Student|    Date    | Classroom |
+-------+------------+-----------+
|     1 | 2018-01-01 |       101 |
|     1 | 2018-03-01 |       104 |
|     1 | 2018-11-01 |       106 |
+-------+------------+-----------+

现在,让我们说6月份我们试图找到小于或等于2018-06-01的月份来获得所需的房间号码。我希望这会有所帮助。