android group by

好比要用實現這麼一個sql語句:
SELECT _id, number, date, duration, type, name, numbertype,
numberlabel, COUNT(*) FROM calls  GROUP BY number,type,date/8640000
ORDER BY date DESC
這個在通常的SQL編譯工具裏都能正常運行,在ContentRosolver中有些不同。

用ContentRosolver中的query這麼寫:

private static String CALLS_COUNT = "calls_count";
static final String[] CALL_LOG_PROJECTION = new String[] {
           Calls._ID,
           Calls.NUMBER,
           Calls.DATE,
           Calls.DURATION,
           Calls.TYPE,
           Calls.CACHED_NAME,
           Calls.CACHED_NUMBER_TYPE,
           Calls.CACHED_NUMBER_LABEL,
           "COUNT(*) AS " + CALLS_COUNT
   };

String selection = "0==0) GROUP BY ("+
           Calls.NUMBER+"),("+
           Calls.TYPE+"),("+
           Calls.DATE+"/86400000
";  //這裏沒有左邊括號"("和右邊括號")"  程序會本身添加. java

//0==0 一個=號和2個等於均可以.

rosolver.query(QUERY_TOKEN, null, Calls.CONTENT_URI,
               CALL_LOG_PROJECTION, selection, null, Calls.DEFAULT_SORT_ORDER);

注意事項:
1 關鍵字「COUNT, AS, GROUP BY」的大小寫
2 COUNT(*) 後須要跟AS ***
3 Android會將query中的參數整合成一條sql語句,其中會將selection的字符串自動加一個括號,造成 「WHERE
(*******)」的形式,因此要特別注意selection中有括號的狀況
4 GROUP BY後面的字段應該加括號,用逗號隔開。

轉化爲sql語句正確的形式應該以下:
SELECT _id, number, date, duration, type, name, numbertype,
numberlabel, COUNT(*) FROM calls WHERE (0==0) GROUP BY
(number),(type),(date/8640000) ORDER BY date DESC sql

5 此方法在4.0以上系統沒法使用,會出現(!type=4)建議你們使用hashset現將電話號碼查出來,遍歷後添加其餘數據 工具

    

public List<NetiveUser> getAllCallRecord(){
		ContentResolver resolver = context.getContentResolver();
		Cursor cursor = resolver.query(CallLog.Calls.CONTENT_URI, new String[]{CallLog.Calls.NUMBER}, null, null, null);
		return getCallRecord(cursor);
	}
	public List<NetiveUser> getCallRecord(Cursor cursor){
		List<NetiveUser> list = new ArrayList<NetiveUser>();
		if(cursor == null){
			return list;
		}
		
		HashSet<String> set = new HashSet<String>();
		while(cursor.moveToNext()){
			String number = cursor.getString(cursor.getColumnIndex(CallLog.Calls.NUMBER));
			set.add(number);
			
		}
		Iterator iter = set.iterator();
		while(iter.hasNext()){
			String number  = iter.next().toString();
			String type="2";
			netiveUser = new NetiveUser();
			netiveUser.setPhoneNumber(number);
			String times =getCallTiems(number,String.valueOf(type));
			netiveUser.setTimes(times);
			List<NetiveUser> listtime = new ArrayList<NetiveUser>();
			listtime = getDateName(number);
			for(int i=0;i<listtime.size();i++){
				Date time = listtime.get(i).getCtreatetime();
				netiveUser.setCtreatetime(time);
				netiveUser.setUserName(listtime.get(i).getUserName());
				System.out.println("teimesssss--"+time.toString());
			}
			System.out.println("listtime=-----"+listtime);
			list.add(netiveUser);
		}
		
		return list;
	}
相關文章
相關標籤/搜索