简体   繁体   English

MYSQL:选择总和(值)

[英]MYSQL : select sum(value)

I have a table with 2 field like this: 我有一个带有2个字段的表格,如下所示:

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 : 而且我想创建一个sql(3天后的sum(Value_col)-如果有3天或更多的天将是总和,如果少于3天不求和),然后接收如下结果:

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... 只需将YOUR_TABLE更改为表格的名称即可...

I hope this will help you! 我希望这能帮到您!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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