我有一个包含2个参数的表:group_id&名称
CREATE TABLE inf_table (group_id INTEGER NOT NULL, name TEXT NOT NULL);
INSERT INTO inf_table(group_id, name) values (1,'AA');
INSERT INTO inf_table(group_id, name) values (1,'BB');
INSERT INTO inf_table(group_id, name) values (1,'AB');
INSERT INTO inf_table(group_id, name) values (2,'AA');
INSERT INTO inf_table(group_id, name) values (2,'BA');
INSERT INTO inf_table(group_id, name) values (2,'AB');
INSERT INTO inf_table(group_id, name) values (2,'BB');
我运行一个查询,按group_id对结果进行排序,然后命名。 “select_ from inf_table order by group_id,name;” 得到了:
1|AA
1|AB
1|BB
2|AA
2|AA
2|BA
2|BB
但是,我想为显示每个组内名称索引的每一行添加一个索引:
1|1|AA
2|1|AB
3|1|BB
1|2|AA
2|2|AA
3|2|BA
4|2|BB
我怎么能?
由于
答案 0 :(得分:1)
您必须计算同一组中的行并在当前名称之前具有名称:
SELECT (SELECT COUNT(*)
FROM inf_table AS inf2
WHERE inf2.group_id = inf_table.group_id
AND inf2.name <= inf_table.name ) AS "index",
group_id,
name
FROM inf_table
ORDER BY group_id,
name
(在程序中读取行时计算行数可能更有效。)