2016-09-27 63 views
1

使用以下代碼來獲取過去兩個月的數據。無法使用sqlite查詢獲取過去兩個月的數據

public List<String> getDates() { 
     SQLiteDatabase db  = this.getReadableDatabase(); 
     List<String> dateList = new ArrayList<>(); 

     String query = "SELECT DISTINCT " + KEY_PROGRESSDATE + " FROM " + TABLE_ENTRY + " WHERE progressdate >= date('now','start of month','-1 month') AND progressdate < date('now','start of month') desc"; 

     Cursor c = db.rawQuery(query, null); 
     if (c.getCount() > 0) { 
      while (c.moveToNext()) { 
       dateList.add(c.getString(0)); 
      } 
     } 
     return dateList; 
    } 

但即時得到的follwing錯誤消息..

引起:android.database.sqlite.SQLiteException:近 「desc」 的: 語法錯誤(碼1):在編譯: SELECT DISTINCT progressdate 從入門WHERE progressdate> =日期( '現在', '一個月的開始',「 - 1 一個月)和progressdate <日期( '現在', '月開始')遞減

爲什麼是這樣?

+0

嘗試thisSELECT DISTINCT progressdate從入門WHERE progressdate> =日期(「現在」,'開始月份',' - 1個月')AND progressdate

回答

2

處理這個例外,你必須寫ORDER BY "Columname" DESC

在這裏,它會像

SELECT DISTINCT progressdate FROM entry WHERE progressdate >= date('now','start of month','-1 month') AND progressdate < date('now','start of month') ORDER BY progressdate desc 

檢查example here

+0

如果這樣可以解決您的問題,請您接受答案嗎?@Learner –

1

你不是在查詢中使用任何Order By子句是。也許你正在試圖按降序排列進度日期?

String query = "SELECT DISTINCT " + KEY_PROGRESSDATE + " FROM " + TABLE_ENTRY + " WHERE progressdate >= date('now','start of month','-1 month') AND progressdate < date('now','start of month') ORDER BY progressdate desc"; 
1

嘿爲什麼要使用原始查詢如果功能已經存在。嘗試以下功能得到任何表中的值只是通過它的參數:

public String[] getValues(boolean b, String table, String column, 
           String where, String orderBy) { 
     ArrayList<String> savedAns = new ArrayList<String>(); 
     Cursor result = null; 
     String[] y; 
     try { 
      result = db.query(b, table, new String[]{column}, where, null, 
        null, null, orderBy, null); 
      if (result.moveToFirst()) { 
       do { 
        savedAns.add(result.getString(result.getColumnIndex(column))); 
       } while (result.moveToNext()); 
      } else { 
       return null; 
      } 
      y = savedAns.toArray(new String[result.getCount()]); 
     } finally { 
      result.close(); 
     } 
     return y; 
    } 

希望它可以幫助你..

相關問題