简体   繁体   中英

MYSQL : select sum(value)

I have a table with 2 field like this:

Day_col   | Value_col
2013-06-06  1
2013-06-05  2
2013-06-04  3
2013-06-03  4
2013-06-02  5

And I want to create a sql (sum(Value_col) of 3 days after - if have 3 days or more will be sum, if less 3 days don't sum ) and then receive the result like this :

Day_col   | total
2013-06-06  9     <- total after '2013-06-06' 3 days are 5,4,3 is 9
2013-06-05  12    <- total after '2013-06-05' 3 days are 4,3,2 is 12
2013-06-04  --    <- total after '2013-06-04' 2 days don't sum
2013-06-03  --    <- total after '2013-06-03' 1 days don't sum
2013-06-02  --    <- total after '2013-06-02' 0 days don't sum

Please, help

SELECT
    Day_col,
    IF (
        (SELECT COUNT(Value_col) FROM myTable AS subT WHERE subT.Day_col < t.Day_col) >= 3,
        (SELECT SUM(Value_col) FROM myTable AS subT WHERE subT.Day_col < t.Day_col and DATE_ADD(subT.Day_col, INTERVAL 3 DAY) >= t.Day_col),
        '--'
    ) AS total
FROM
    myTable t
CREATE TABLE foo
    (`Day_col` varchar(10), `Value_col` int)
;

INSERT INTO foo
    (`Day_col`, `Value_col`)
VALUES
    ('2013-06-06', 1),
    ('2013-06-05', 2),
    ('2013-06-04', 3),
    ('2013-06-03', 4),
    ('2013-06-02', 5)
;

SELECT
Day_col,
IF (
(SELECT COUNT(Value_col) FROM foo AS sf WHERE sf.Day_col < f.Day_col) >= 3,
(SELECT SUM(Value_col) FROM foo AS sf WHERE sf.Day_col >= f.Day_col - INTERVAL 3 DAY and sf.Day_col < f.Day_col),
'--'
) AS total
FROM
foo f;

Result:

DAY_COL     TOTAL
2013-06-06  9
2013-06-05  12
2013-06-04  --
2013-06-03  --
2013-06-02  --

To make the query cleaner, i would suggest you to create a simple function:

DELIMITER $$
DROP FUNCTION IF EXISTS `getSum`$$
CREATE FUNCTION `getSum`(a DATE) RETURNS INT DETERMINISTIC
    BEGIN

        DECLARE ret INT DEFAULT 0;
        DECLARE ct INT DEFAULT 0;

        SELECT COUNT(Day_col), COALESCE(SUM(Value_col),0) INTO ct, ret 
        FROM YOUR_TABLE WHERE Day_col < a AND Day_col >= DATE_SUB(a,INTERVAL 3 DAY);

        IF(ct>=3) THEN RETURN ret;
        ELSE RETURN NULL;
        END IF;

    END$$

DELIMITER ;

And then, just use the query:

SELECT Day_col, IF(getSum(Day_col) IS NOT NULL, getSum(Day_col), '--') AS total FROM YOUR_TABLE

or if you want to exclude the days '--':

SELECT Day_col, getSum(Day_col) AS total FROM YOUR_TABLE WHERE getSum(Day_col) IS NOT NULL

Just change YOUR_TABLE to your table's name...

I hope this will help you!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM