对sqlite记录进行分组和排序

时间:2013-06-17 07:00:16

标签: android sqlite android-sqlite

我有一张包含以下cols的表

_id INTEGER PRIMARY KEY,
body TEXT,
category TEXT,
is_readed INTEGER,
date INTEGER

我有记录查看示例

我有以下查询

SELECT
    _id, body, category, is_readed
FROM 
    table
GROUP BY
    category
ORDER BY
    category, is_readed, date DESC

我希望show 仅显示类别的第一条记录(无论is_readed是0还是1),但我希望首先显示(如果存在)带有is_readed == 1的记录。但有时会显示is_readed == 0的第一条记录,即使存在is_readed == 1

的记录

注意:我正在使用ContentProvider而不是原始查询

更新

用这个粗略的工作尝试了一段时间后

SELECT
    _id, body, category, MIN(is_readed) as is_readed
FROM 
    table
GROUP BY
    category
ORDER BY
    category, date DESC

我仍在进行测试,但我仍然不相信

实施例

SELECT * FROM table ORDER BY category, is_readed ASC, date DESC;

_id|category|body|is_readed|date
19|Hogar|message1|1|1371449889136
16|Hogar|message2|1|1371449806704
15|Hogar|message2|1|1371449803825
11|Hogar|message3|1|1371448915930
5|Hogar|message4|1|1371447395055
4|Hogar|message4|1|1371447391394
23|Linea blanca|message2|0|1371450430216
26|Linea blanca|message1|1|1371450719124
24|Linea blanca|message4|1|1371450431604
21|Linea blanca|message1|1|1371449893835
20|Linea blanca|message1|1|1371449891488
17|Linea blanca|message3|1|1371449810104
13|Linea blanca|message3|1|1371448994173
12|Linea blanca|message2|1|1371448917864
6|Linea blanca|message4|1|1371447397387
22|Vehiculos|message3|0|1371450428817
14|Vehiculos|message3|0|1371449801144
25|Vehiculos|message4|1|1371450717115
18|Vehiculos|message4|1|1371449887682
10|Vehiculos|message1|1|1371448422563
9|Vehiculos|message4|1|1371448419438
8|Vehiculos|message3|1|1371448416315
7|Vehiculos|message4|1|1371448395644
3|Vehiculos|message3|1|1371447388887
2|Vehiculos|message1|1|1371447386126
1|Vehiculos|message2|1|1371447383557

我的更新

SELECT
    _id, body, category, MIN(is_readed) as is_readed
FROM 
    table
GROUP BY
    category
ORDER BY
    category, date DESC

_id|category|body|is_readed|date
4|Hogar|message4|1|1371447391394
23|Linea blanca|message2|0|1371450430216
14|Vehiculos|message3|0|1371449801144

@Hoan Nguyen回答

4|Hogar|message4|1|1371447391394
6|Linea blanca|message4|1|1371447397387
1|Vehiculos|message2|1|1371447383557

预期结果

19|Hogar|message1|1|1371449889136
23|Linea blanca|message2|0|1371450430216
22|Vehiculos|message3|0|1371450428817

2 个答案:

答案 0 :(得分:0)

我必须在我的ContentProvider和子查询中实现原始查询,但我认为可以在没有子查询的情况下执行

SELECT
    _id, body, category, is_readed, date
FROM
(
    SELECT
        _id, body, category, is_readed, date
    FROM 
        table
    GROUP BY
        is_readed, category
    ORDER BY
        category ASC, is_readed DESC, date DESC
)
GROUP BY
    category

答案 1 :(得分:-1)

SELECT
    _id, body, category, is_readed
FROM 
    table
GROUP BY
    category
HAVING 
    max (is_readed)
ORDER BY
    category, is_readed, date DESC