【发布时间】:2013-05-09 14:00:32
【问题描述】:
我有下表:
| id | Name | Date of Birth | Date of Death | Result |
| 1 | John | 3546565 | 3548987 | |
| 2 | Mary | 5233654 | 5265458 | |
| 3 | Lewis| 6546876 | 6548752 | |
| 4 | Mark | 6546546 | 6767767 | |
| 5 | Steve| 6546877 | 6548798 | |
而且我需要为整个表格执行此操作:
Result = 1, if( current_row(Date of Birth) - row_above_current_row(Date of Death))>X else 0
我想,为了让事情更简单,我在上面创建了同一个表,但有 2 个额外的 id 字段:id_minus_one 和 id_plus_one
像这样:
| id | id_minus_one | id_plus_one |Name | Date_of_Birth | Date_of_Death | Result |
| 1 | 0 | 2 |John | 3546565 | 3548987 | |
| 2 | 1 | 3 |Mary | 5233654 | 5265458 | |
| 3 | 2 | 4 |Lewis| 6546876 | 6548752 | |
| 4 | 3 | 5 |Mark | 6546546 | 6767767 | |
| 5 | 4 | 6 |Steve| 6546877 | 6548798 | |
所以我的方法类似于(在伪代码中):
对于 id=1,忽略结果。 (因为上面没有行)
对于 id=2,结果 = 1 if( (其中 id=2).Date_of_Birth - (其中 id_minus_one=id-1).Date_of_Death )>X else 0
对于 id=3,结果 = 1 if( (其中 id=3).Date_of_Birth - (其中 id_minus_one=id-1).Date_of_Death)>X else 0
整张桌子以此类推...
如果不需要 id_plus_one 就忽略它,我稍后会用它来做同样的事情。因此,如果我设法为 id_minus_one 执行此操作,我将为 id_plus_one 执行此操作,因为它们是相同的算法。
我的问题是如何将该伪代码传递到 SQL 代码中,我无法找到一种方法在一次选择中关联两个 id。
谢谢!
【问题讨论】:
标签: mysql sql row subtraction