2014-10-16 118 views
0

我试图从上月总结大量打字(SET)如何计算上个月的数值?

这里的结构:

CREATE TABLE tester (
date_amount date, 
amount int); 


INSERT INTO tester VALUES 
("2014-08-01", 1000), 
("2014-08-02", 1001), 
("2014-08-03", 1002), 
("2014-08-31", 2000), 
("2014-08-31", 2000), 
("2014-08-31", 2000), 
("2014-09-01", 1006); 
在例如例如

这里

如果键入年= 2014月= 9,我应该会自动总结在这种情况下键入的所有金额每月的最后一天“2014年8月31日”

这里是demo

SET @month := 09; 
SET @year := 2014; 

select sum(amount) from tester 
where month(date_amount)= @month-1 

查询必须总结前一个月的最后一天的所有款项类型

我必须为结果是:

SUM(AMOUNT) 
6000 

我试过,但不是正确的方式,因为在这里我知道该月的最后一天:

SET @month := 09; 
SET @year := 2014; 

select sum(amount) from tester 
where month(date_amount)= @month-1 and day(date_amount)= 31 

我也试过此查询,但得到NULL

SET @month := 09; 
SET @year := 2014; 

SELECT sum(amount)FROM tester 
WHERE month(date_amount)= @month-1 AND day(date_amount) =last_day(day(date_amount)) 

请有人可以帮助我呢?

回答

1

而不是仅仅提供月份和年份提供一个实际的日期,然后你可以得到你想要

结果
SET @month := 09; 
SET @year := 2014; 

SELECT sum(amount)FROM tester 
WHERE month(date_amount)= @month-1 AND day(date_amount) = day(last_day(date_amount)) 

或者,你可以使用STR_TO_DATE转换的年份和月份给出的最新第一,并使用该而不是@Date

+0

很高兴能帮到你! :D – 2014-10-16 18:03:04

+0

@ThanatosSama我刚刚注意到你几乎有正确的答案。如果你将where子句的第二个条件改为day(last_day(date_amount)),那么在第二次尝试中你得到了'null'。你得到空的原因是因为last_day返回的日期不会等于'day'返回的日期(整数)。 – 2014-10-16 18:16:47

+0

哦,对不起,我没有注意到你写了@日期我不想只输入日期和月份。 – 2014-10-17 14:05:24

0

而不是使用一个月只使用年份和月份与TO_CHAR(YYYYMM)

select sum(amount) 
from tester 
group by to_char(date_amount, 'YYYYMM'); 

在MySQL中,你可以使用DATE_FORMAT(date_amount, '%Y%M')的第一天和最后一天,而不是的TO_CHAR

+0

查询必须总结前一个月的最后一天的所有款项类型 – 2014-10-16 17:30:48

1

事情是这样的:

SELECT SUM(AMOUNT) FROM Tester 
WHERE date_amount = LAST_DAY(STR_TO_DATE(@Month + '/00/' + @Year, '%m/%d/%Y')) 

如果您在表中的行的部分使用功能,将强制SQL做一个表扫描。如果将数据转换为完整字段,则可以在搜索中使用索引。

+0

我想你的代码,但得到了NULL http://sqlfiddle.com/#!2/6b7e19/36 – 2014-10-16 17:53:20

+0

你是附近到答案,但我发现如果翻译是回归将返回NULL,但感谢您的帮助。 – 2014-10-16 18:00:59

1

这可能会帮助:

SET @month := 09; 
SET @year := 2014; 

SELECT sum(amount) FROM tester 
WHERE month(date_amount)= @month-1 and date_amount = last_Day(date_amount) 
1

如前所述,最好不先来比较列底肥功能

SET @month = '09', @year = '2014'; 

SELECT 
    SUM(amount) total 
FROM 
    tester 
WHERE 
    date_amount = STR_TO_DATE(CONCAT_WS('-', @year, @month, '01'), '%Y-%m-%d') - INTERVAL 1 DAY 
+0

感谢这是另一个不错的选择+1。 – 2014-10-20 17:28:49