3

我使用 mysql 存储过程,我怎样才能创建一个循环,每 1 小时变量 strhour 将有 1 小时间隔,然后返回查询的总输出。虽然 starthour 小于 11 月的日期,但它将间隔 1 小时并执行查询。

这是我的代码:

DELIMITER $$

CREATE DEFINER=`root`@`%` PROCEDURE `sp_asessiontime`(
out `total` int
)
BEGIN

declare `starthour`, `endhour` datetime;
set `starthour` = '2012-09-20 01:59:00';
set `endhour` = '2012-09-20 02:00:00';


select count(terminalcount.terminalids) into total from (
select distinct ts.TerminalID `terminalids` from
tmptransactiondetails td
inner join transactionsummary ts
on td.TransactionSummaryID = ts.TransactionsSummaryID
where
td.ServiceID = 4
and
td.TransactionType in ('D','W')
and
(ts.DateStarted >= starthour and ts.DateStarted < endhour)
or
(ts.DateEnded >= starthour and ts.DateEnded < endhour)
or
(ts.DateStarted < starthour and starthour <= ts.DateEnded)
)as terminalcount;

-- 每1小时循环一次

while 

starthour < '2012-11-01 01:59:00' do
select starthour + interval 1 hour;
select total as totalnumber;

end while;

END

十分感谢大家。

4

1 回答 1

9

我不确定我是否正确地回答了您的问题,但这就是您在日期之间循环的方式

set currHour = '2012-09-20 01:59:00';
set endhour = '2012-09-21 02:00:00';

REPEAT

-- execute your queries for every hour

Set currHour = DATE_ADD(currHour,INTERVAL 1 HOUR);
UNTIL currHour > endhour END REPEAT;

如果必须使用 while 循环:

WHILE currHour < endhour DO
  -- execute your queries for every hour
  Set currHour = DATE_ADD(currHour,INTERVAL 1 HOUR);
END WHILE;
于 2012-11-09T09:46:58.063 回答