当前位置: 代码迷 >> PB >> contentProvider兑现groupby查询数据
  详细解决方案

contentProvider兑现groupby查询数据

热度:5   发布时间:2016-04-29 08:14:03.0
contentProvider实现groupby查询数据
比如要用实现这么一个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";

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

  相关解决方案