mysql存储过程中的总值

时间:2013-02-27 17:00:22

标签: mysql stored-procedures

我试图从我的数据库中获取具有不同日期时间戳的值的总和。我的目标是返回该日期表中所有值的每一天的总数。我的商店程序如下所示:

DELIMITER //
DROP PROCEDURE get_reads;
CREATE PROCEDURE get_reads (IN  device varchar (20), IN start_date datetime, IN end_date datetime, IN read_type varchar(8))

BEGIN

    SELECT dr.date_time, sum(dr.device_reading)
    FROM DEVICE_DETAILS dd,
    DEVICE_READING dr
    WHERE dr.device_id = dd.device_id
    AND dd.serial_number = device
    AND dr.date_time BETWEEN start_date AND end_date
    AND dr.reading_type = read_type;



END//

我相信我将不得不使用临时表或其他东西,但无法在网上找到有关我的情况的任何建议。每天我都有一个值每半小时我希望存储的程序在每天内返回这些总计我传入的日期范围。数据库列看起来像这样

+-----------+---------------------+--------------+----------------+-------+
| device_id | date_time           | reading_type | device_reading | units |
+-----------+---------------------+--------------+----------------+-------+
| E1        | 2012-11-19 00:29:00 | Profile      |   0.0719131800 | KW    |
| E1        | 2012-11-19 00:59:00 | Profile      |   0.0802306700 | KW    |
| E1        | 2012-11-19 01:29:00 | Profile      |   0.0767434100 | KW    |
| E1        | 2012-11-19 01:59:00 | Profile      |   0.0737920500 | KW    |
| E1        | 2012-11-19 02:29:00 | Profile      |   0.0794256700 | KW    |
| E1        | 2012-11-19 02:59:00 | Profile      |   0.0729868200 | KW    |
| E1        | 2012-11-19 03:29:00 | Profile      |   0.0745970500 | KW    |
| E1        | 2012-11-19 03:59:00 | Profile      |   0.0804993100 | KW    |
| E1        | 2012-11-19 04:29:00 | Profile      |   0.0837193100 | KW    |
| E1        | 2012-11-19 04:59:00 | Profile      |   0.0483004600 | KW    |

1 个答案:

答案 0 :(得分:0)

使用CAST解决(datetime AS DATE);

DELIMITER //
DROP PROCEDURE get_reads;
CREATE PROCEDURE get_reads (IN  device varchar (20), IN start_date datetime, IN end_date datetime, IN read_type varchar(8))

    BEGIN

            SELECT dr.date_time, sum(dr.device_reading)
            FROM DEVICE_DETAILS dd,
            DEVICE_READING dr
            WHERE dr.device_id = dd.device_id
            AND dd.serial_number = device
            AND dr.date_time BETWEEN start_date AND end_date
            AND dr.reading_type = read_type
            GROUP BY CAST(dr.date_time AS DATE);



    END//