我如何获得本周的数据?

时间:2018-05-19 17:11:33

标签: sql objective-c sqlite date datetime

我正在尝试编写一个方法,该方法将返回表格“费用”中所有费用的总和,但是在当前一周(周一作为第一周的一周)

这就是我的数据库的样子:

enter image description here

这是我里面的数据

enter image description here

我有这样的事情:

- (float)getthisweekscosts {
    float sumprice = 0; // We initialize the total price for all the rows

    NSString *getcurrentcost = [NSString stringWithFormat:@"%@", @"SELECT COSTAMOUNT FROM COST WHERE DATE > DATE('now', 'weekday 0', '-7 days')"];
    const char *query_stmt_budget = [getcurrentcost UTF8String];

    if (sqlite3_prepare_v2(costDB,query_stmt_budget, -1, &statement, NULL) == SQLITE_OK){
        while (sqlite3_step(statement) == SQLITE_ROW){
            NSString *currentcost = [NSString stringWithFormat:@"%s",(const char *) sqlite3_column_text(statement, 0)];
            sumprice += [currentcost floatValue];
        }
        sqlite3_finalize(statement);
    }

    sqlite3_close(costDB);

    return sumprice;
}

来源:Get this week's data using SQLite

但我不确定为什么它会在我的情况下返回0。

1 个答案:

答案 0 :(得分:1)

检查COSTDATE列类型DATE'?

如果这是真的,那么您就不需要DATE(COSTDATE)

使用COSTDATE

你的数据和sql是对的

这是测试演示

CREATE TABLE COST(
    COSTAMOUNT  REAL,
    COSTDATE DATE
);

INSERT INTO COST VALUES (2.48,'2018/05/19');
INSERT INTO COST VALUES (2.85,'2018/05/19');
INSERT INTO COST VALUES (null,null);


SELECT sum(COSTAMOUNT) --result 5.33
FROM COST 
WHERE COSTDATE > DATE('now', 'weekday 0', '-7 days') 

SQL Fiddle

调试并检查您的代码

if (sqlite3_prepare_v2(costDB,query_stmt_budget, -1, &statement, NULL) == SQLITE_OK){

while (sqlite3_step(statement) == SQLITE_ROW){

    NSString *currentcost = [NSString stringWithFormat:@"%s",(const char *) sqlite3_column_text(statement, 0)];
    sumprice += [currentcost floatValue];
}
sqlite3_finalize(statement);
}