在ContentResolver中使用Group By,contentresolver

來源:互聯網
上載者:User

在ContentResolver中使用Group By,contentresolver

使用ContentProvider查詢簡訊,希望可以在ContentResolver.query中使用Group By ,發現系統並沒有提供介面或者可用欄位。

探究竟

首先我們來看看query函數:

public final Cursor query(Uri uri, String[] projection,        String selection, String[] selectionArgs, String sortOrder) {    return query(uri, projection, selection, selectionArgs, sortOrder, null);}

最有可能可以處理的地方就是selection,我們首先嘗試設定 selection = "gourp by thread_id" 執行程式,從錯誤記錄檔中發現,sql語句經過編譯處理加上了括弧,像下面這樣:

SELECT _id, thread_id, address, person, body, date FROM sms WHERE (type=1) AND (group by thread_id) ORDER BY date DESC

看來要最終得到正確的sql語句,selection的設定需要有技巧性一些。再嘗試selection = "0=0) group by (thread_id",這次成功了!主要是注意括弧的處理,以及AND後面必須有一個查詢條件,這裡我們使用了0=0(此處驗證0==0亦可)這個永真查詢只是為了保證sql語句的正確性。

最後處理效果如下:

Uri SMS_PROVIDER = Uri.parse("content://sms/inbox");String[] projection = new String[] {  "_id", "thread_id", "address",  "person", "body", "date"};Cursor cursor = context.getContentResolver().query(SMS_PROVIDER,  projection, "0=0) group by (thread_id", null, "date desc");

這樣,經過編譯處理之後的sql語句為:

SELECT _id, thread_id, address, person, body, date FROM sms WHERE (type=1) AND (0=0)group by (thread_id) ORDER BY date DESC

 


SQL中GROUP BY的用法

GROUP BY 是分組查詢, 一般 GROUP BY 是和 彙總函式配合使用,你可以想想

你用了GROUP BY 按 ITEM.ITEMNUM 這個欄位分組,那其他欄位內容不同,變成一對多又改如何顯示呢,比如下面所示

A B
1 abc
1 bcd
1 asdfg

select A,B from table group by A
你說這樣查出來是什麼結果,

A B
    abc
1 bcd
    asdfg

右邊3條如何變成一條,所以需要用到彙總函式,比如

select A,count(B) 數量 from table group by A
這樣的結果就是
A 數量
1 3

group by 有一個原則,就是 select 後面的所有列中,沒有使用彙總函式的列,必須出現在 group by 後面
 
sql語句中 group by用法

select id,name from tab
where name in
(select distinct name from tab)
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.