簡體   English   中英

如何匯總上個月的值?

[英]How can sum values from the previous month?

我正在嘗試匯總上個月鍵入(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);

這里以示例為例

如果我鍵入year = 2014且month = 9,則在這種情況下,我應自動求和該月中的最后一天的總和,“ 2014-08-31”

這是演示

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))

請有人可以幫助我嗎?

像這樣:

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

如果在表的行的一部分上使用函數,則強制sql執行表掃描。 如果將數據轉換為完整字段,則可以在搜索中使用索引。

不僅僅是提供月份和年份,而是提供實際日期,然后您可以獲得所需的結果

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

這可能會有所幫助:

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

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

如前所述,最好在不首先應用函數的情況下比較列

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  

而不是使用月份的第一天和最后一天,而只將年份和月份與TO_CHAR(YYYYMM)一起使用

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

在Mysql中,您可以使用DATE_FORMAT(date_amount,'%Y%m')代替to_char

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM