0

我有一个在 EID(事件 ID)和 start_time 上具有复合主键的表。我还有一个专栏叫出席。

用户通过重用事件 ID 和更改日期来使他们的事件更受欢迎,但是,在本例中,我在数据库中创建了一个新行。

我想创建第四列,actual_attending,它等于出席值减去上一个事件的出席值。如果它们不是以前的 ID,则该列可以为空。我如何通过更新来计算这个。

这里以 sqlfiddle 为例:http ://sqlfiddle.com/#!2/43f2c5

4

2 回答 2

0
SELECT a.*
     , a.attending-b.attending new_actual_attending
  FROM 
     ( SELECT x.*
            , COUNT(*) rank
         FROM event x
         JOIN event y
           ON y.eid = x.eid
          AND y.start_time <= x.start_time
        GROUP
           BY eid, start_time
     ) a
  LEFT
  JOIN 
     ( SELECT x.*
            , COUNT(*) rank
         FROM event x
         JOIN event y
           ON y.eid = x.eid
          AND y.start_time <= x.start_time
        GROUP
           BY eid, start_time
     ) b
    ON b.eid = a.eid
   AND b.rank = a.rank - 1;

   +-----+------------+-----------+------------------+------+----------------------+
   | eid | start_time | attending | actual_attending | rank | new_actual_attending |
   +-----+------------+-----------+------------------+------+----------------------+
   |   1 | 2013-06-08 |        29 |             NULL |    1 |                 NULL |
   |   2 | 2013-06-09 |        72 |             NULL |    1 |                 NULL |
   |   2 | 2013-06-16 |       104 |             NULL |    2 |                   32 |
   |   3 | 2013-06-07 |       224 |             NULL |    1 |                 NULL |
   |   3 | 2013-06-14 |       222 |             NULL |    2 |                   -2 |
   +-----+------------+-----------+------------------+------+----------------------+

http://sqlfiddle.com/#!2/43f2c5/2

于 2013-06-11T23:22:37.863 回答
0
update event e1
set e1.actual_attending = (select e1.attending - e2.attending
                           from event e2
                           where e2.eid(+) = e1.previous_eid
                          )
于 2013-06-11T20:51:36.090 回答