0

I am using the following SELECT statement within a cursor in a procedure.

SET @chng = (   SELECT Tcle - cls 
                FROM dly
                WHERE dt = SUBDATE(Tdt, INTERVAL 1 DAY);
                AND dly.nms_id = Tnms_id);

Tdt is the date of the current record.

The problem I have is that the records in my table do not have consecutive dates. So records in dly will have dates '11-01-2010' then '12-01-2010' and then '15-01-2010' due to the weekend between.

That is where my SELECT statement is flawed as if it is run on '15-01-2010' as Tdt, then:

WHERE dt = '14-01-2010'

but I want it to select the previous records date:

WHERE dt = '12-01-2010'

So is there a way to SELECT the previous records date?

4

2 回答 2

2

在这种情况下,我将取所有日期早于指定行的行,按日期列按降序对它们进行排序,然后只取最后一个,如下所示(突出显示对当前语句的必要更改) :

SET @chng = (   SELECT Tcle - cls 
                FROM dly
                WHERE dt < Tdt
                AND dly.nms_id = Tnms_id
                ORDER BY dt DESC
                LIMIT 1);
于 2013-04-19T09:18:19.803 回答
0

使用以下查询

选择 MAX(Tcle - cls) 从 dly WHERE dt < Tdt AND dly.nms_id = Tnms_id

于 2013-04-18T11:17:31.410 回答