从查询中获取所有行

时间:2017-05-12 14:07:58

标签: android sqlite group-by

我有数据库sqlite包含2个表:

名称

Table with two columns. The column id contains numbers and the column name contains strings.

N_DATA

Table with three columns. The column id contains numbers, the column name_id contains numbers, and the column value contains strings.

和查询:

select 
    n_data.id,n_data.value, count( n_data.id) as count 
from 
    n_data 
INNER JOIN names on names.id = n_data.name_id 
group by 
    n_data.name_id 
order by 
    n_data.id asc

在我使用过的活动中 光标和

 while (res.moveToNext()) {
      System.out.println("id=>"+res.getString(0)+" count=>"+res.getString(2)+" =value=>"+res.getString(1));
 }

但结果只显示组中的最后一行。如何获取每个组的所有行?

CREATE TABLE "names" (
    id  INTEGER PRIMARY KEY AUTOINCREMENT,  
    name    TEXT );
INSERT INTO names (id,name) VALUES  
(1,'name_1'),  
(2,'name_2'),  
(3,'name_3'),  
(4,'name_4');  
CREATE TABLE "n_data" (
    id  INTEGER PRIMARY KEY AUTOINCREMENT,  
    name_id TEXT,  
    value   TEXT );  
INSERT INTO n_data (id,name_id,value) VALUES  
(1,'3','value_8'),  
(2,'2','value_7'),  
(3,'2','value_6'),  
(4,'2','value_5'),  
(5,'1','value_4'),  
(6,'1','value_3'),  
(7,'1','value_2'),  
(8,'1','value_1'),  
(9,'3','value_9');

1 个答案:

答案 0 :(得分:0)

OP满意:

select 
    n_data.id,
    group_concat(n_data.value) as 'all values',
    count( n_data.id) as count
from
    n_data INNER JOIN names 
    on names.id = n_data.name_id
group by n_data.name_id
order by n_data.id asc;

它使用group_concat(n_data.value)代替n_data.value 即所有由count(n_data.id)计算的data.value都会被连接起来。

输出(.headers on.mode column.width 3 32 6; SQLite 3.18.0 2017-03-28):

id   all values                        count
---  --------------------------------  ------
4    value_7,value_6,value_5           3
8    value_4,value_3,value_2,value_1   4
9    value_8,value_9                   2

需要定制.width,否则对于id 8,只显示3个值,但会检索4个。