尝试使用case语句为列设置不同的值

时间:2013-12-29 17:39:51

标签: mysql stored-procedures

如果完成日期在startdate之前,我试图在第一行设置冷却小时的值  样本数据

row       completed              next_completed     cooling Hours
Num 
9   11/25/2013 11:21:15 PM  11/27/2013 1:05:45 AM   25.7417
10  11/27/2013 1:05:45 AM   11/29/2013 11:18:34 PM  (null)
11  11/29/2013 11:18:34 PM  11/30/2013 7:37:45 PM   20.3197
12  11/30/2013 7:37:45 PM   11/30/2013 11:36:57 PM  (null)
13  11/30/2013 11:36:57 PM  12/1/2013 6:52:19 PM    19.2561
在上面的示例日期中,coolingHours =每行的next_Completed和completed之间的时差 但是对于ROW 9,我需要将coolingHours设置为next_completed和startDate之间的时差 - 所有其他行保持不变

startDate是传递给storedProcedure的变量(对于此示例,它将是11 /// 2013)

我尝试了下面的代码但是它只返回了min(rowNum)并且它没有影响coolingHours

SELECT   rowNum, 
   l.logId,l.completed,l.next_completed,l.first_completed,
    isError,charge,totalTimeRange,startingDate,endingDate,
     CASE
        WHEN completed < ''',startDate,''' AND rowNum = min(rowNum)
            THEN time_to_sec(timediff(l.next_completed, ''',startDate,''')) / 3600
            ELSE coolingHours
        END AS coolingHours,
    databaseName,i.name,l.itemId, kwDifference, cost, costT,l.details,timeInSeconds
  FROM tempTable3 l
   inner join items i ON l.logId = i.logId AND i.name LIKE ''%KW PRE%'' 
   WHERE l.itemId = ''',myItemId,''' 
          AND completed BETWEEN ''', startDate, ''' AND ''', endDate, '''

我愿意接受这方面的建议!

1 个答案:

答案 0 :(得分:0)

添加以下代码修复了问题

   set @newcoolingHours = (SELECT time_to_sec(timediff(next_completed, startDateOriginal)) / 3600 AS newCoolingHours 
        FROM tempTable3 WHERE completed > startDateOriginal AND completed BETWEEN startDate AND endDate LIMIT 1);
   SET xHours = @newCoolingHours;

完整代码:

 set @newcoolingHours = (SELECT time_to_sec(timediff(next_completed, startDateOriginal)) / 3600 AS newCoolingHours 
        FROM tempTable3 WHERE completed > startDateOriginal AND completed BETWEEN startDate AND endDate LIMIT 1);
   SET xHours = @newCoolingHours;

  SET @sqlTemp = NULL;
  SET @sqlTemp = 
   CONCAT(
  'SELECT   rowNum,
   IF ((DAYOFYEAR(completed) = DAYOFYEAR(''',startDate,''') ),''',xHours,''',coolingHours)AS coolingHours,
   l.completed,DAYOFYEAR(completed)AS completedDayOfYear,
    ''',startDateOriginal,''' AS OriginalStartDate,DAYOFYEAR(''',startDateOriginal,''')AS originalDayOfYear,
    ''',startDate,''' AS newStartDate,DAYOFYEAR(''',startDate,''')AS startDateDayOfYear,
    l.next_completed,DAYOFYEAR(  l.next_completed)AS nextCompletedDayOfYear,

    isError,charge,totalTimeRange,startingDate,endingDate,
    l.logId, l.first_completed,databaseName,i.name,l.itemId, kwDifference, cost, 
    costT,l.details,timeInSeconds
  FROM tempTable3 l
   inner join items i ON l.logId = i.logId AND i.name LIKE ''%KW PRE%'' 
   WHERE l.itemId = ''',myItemId,''' 
          AND completed BETWEEN ''', startDate, ''' AND ''', endDate, '''

 ');