3

我想为两个日期(@sdate,@edate)之间的每个日期提取一个计数,但它只给我最后一天的计数,而不是所有天的计数。

如何输出所有结果?这是我的存储过程。

DELIMITER $$
USE `cmd_storeinfo`$$
DROP PROCEDURE IF EXISTS `test2`$$
CREATE DEFINER=`USER`@`%` PROCEDURE `test2`()
BEGIN
  SET @sdate = (DATE_SUB(CURDATE(), INTERVAL 6 MONTH));
  SET @edate = (CURDATE());
  SET @x='';
  SET @Y='';
    WHILE @sdate <= @edate DO
       SELECT COUNT(*) INTO @y
       FROM cmd_storeinfo.strinfo 
       WHERE LiveDate <= @sdate AND DeinstallDate >= @sdate OR DeinstallDate IS
             NULL AND LiveDate IS NOT NULL
             AND CHAIN != 1 && CHAIN != 2 && CHAIN != 999
       GROUP BY @sdate
         SET @x = @sdate;
         SET @sdate = (DATE_ADD(@sdate, INTERVAL 1 DAY));
   END WHILE;
SELECT @x,@y;
END$$
DELIMITER ;

谢谢你的帮助。丹尼尔

4

2 回答 2

0

您应该尝试使用临时表。这是一个很好的答案

像这样的东西可以工作:

DELIMITER $$
USE `cmd_storeinfo`$$
DROP PROCEDURE IF EXISTS `test2`$$
CREATE DEFINER=`USER`@`%` PROCEDURE `test2`()
BEGIN
  CREATE TEMPORARY TABLE tmpTable (currentDate DATE, startDate INT);

  SET @sdate = (DATE_SUB(CURDATE(), INTERVAL 6 MONTH));
  SET @edate = (CURDATE());
  SET @x='';
  SET @Y='';
    WHILE @sdate <= @edate DO
       INSERT INTO tmpTable (currentDate, startDate)
       SELECT @sdate, COUNT(*)
       FROM cmd_storeinfo.strinfo 
       WHERE LiveDate <= @sdate AND DeinstallDate >= @sdate OR DeinstallDate IS
             NULL AND LiveDate IS NOT NULL
             AND CHAIN != 1 && CHAIN != 2 && CHAIN != 999
       GROUP BY @sdate
         SET @sdate = (DATE_ADD(@sdate, INTERVAL 1 DAY));
   END WHILE;
SELECT * FROM tmpTable;

DROP TEMPORARY TABLE IF EXISTS tmpTable;
END$$
DELIMITER ;
于 2012-09-19T11:41:58.593 回答
0

您应该使用临时表来存储所有值。

DELIMITER $$
USE `cmd_storeinfo`$$
DROP PROCEDURE IF EXISTS `test2`$$
CREATE DEFINER=`USER`@`%` PROCEDURE `test2`()
BEGIN
  SET @sdate = (DATE_SUB(CURDATE(), INTERVAL 6 MONTH));
  SET @edate = (CURDATE());
  SET @x='';
  SET @Y='';
  CREATE TEMPORARY TABLE tmpTable (x datetime,y bigint); -- creating tmp table
    WHILE @sdate <= @edate DO
       SELECT COUNT(*) INTO @y
       FROM cmd_storeinfo.strinfo 
       WHERE LiveDate <= @sdate AND DeinstallDate >= @sdate OR DeinstallDate IS
             NULL AND LiveDate IS NOT NULL
             AND CHAIN != 1 && CHAIN != 2 && CHAIN != 999
       GROUP BY @sdate

         SET @x = @sdate;
         insert into tmpTable (x,y) values (@x,@y); -- inserting values
         SET @sdate = (DATE_ADD(@sdate, INTERVAL 1 DAY));
   END WHILE;
SELECT x,y from tmpTable order by x; -- output temp table results
END$$
DELIMITER ;
于 2012-09-19T11:42:18.137 回答