2

i have a table temporary as follow as:

student    |      Data     |    number           
-----------|---------------|--------------
1          |   book        |      2          
1          |   book        |      5    
1          |   book        |      9     
2          |   book        |      1         
2          |   book        |      5     

i will show reduction of column in like as output column as follow as:

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)

how are writing of php's script is correct? because i'm confused

4

2 回答 2

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

这是SQL 小提琴

于 2013-06-12T14:02:59.463 回答
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

SQLFiddle 示例

于 2013-06-12T14:23:33.147 回答