我有一张临时表如下:
student | Data | number
-----------|---------------|--------------
1 | book | 2
1 | book | 5
1 | book | 9
2 | book | 1
2 | book | 5
我将在输出列中显示列的缩减,如下所示:
student | Data | number |output (number column of next row-previous line )
-----------|---------------|----------------|--------------
1 | book | 2 | 0
1 | book | 5 | 3 (result of (5-2=3)
1 | book | 9 | 4 (result of (9-5=4)
2 | book | 1 | 0
2 | book | 5 | 4 (result of (5-1=4)
如何编写php的脚本是正确的?因为我很困惑
答案 0 :(得分:1)
以下脚本将从同一学生的前一个数字中减去该数字。这是你如何在MySQL中实现的(它不支持窗口函数。)
SELECT
t1.student,
t1.Data,
t1.number,
IF (t2.number IS NULL, 0, t1.number - MAX(t2.number)) as output
FROM
tbl t1
LEFT JOIN
tbl t2
ON
t1.student = t2.student
AND t1.number > t2.number
GROUP BY
t1.student, t1.Data, t1.number
答案 1 :(得分:1)
您没有提及您的DBMS,因此这是标准的SQL:
select student,
data,
number,
number - lag(number,1,number) over (partition by student order by id) as output
from the_table
order by student, id