如何获得每行固定数量的结果?

时间:2012-03-27 02:52:28

标签: sql sqlite

如何使用sqlite3数据库构建具有此格式的查询?

CREATE TABLE sample (integer foo);
INSERT INTO sample VALUES (1);
...
INSERT INTO sample VALUES (10);

结果的格式

1,2,3
4,5,6
7,8,9
10

2 个答案:

答案 0 :(得分:2)

您必须添加一些标准才能对它们进行分组:

CREATE TABLE sample (integer foo, char(1) bar);
INSERT INTO sample VALUES
(1, 'a'), (2, 'a'), (3, 'a'), (4, 'b'), (5, 'b'), (6, 'b'), (7, 'c') ...;

SELECT GROUP_CONCAT(foo ORDER BY foo, ',')
FROM sample
GROUP BY bar

修改

试试这个:

select group_concat(foo) from (
  select s1.foo, (count(*) - 1) / 3 grp from sample s1
  join sample s2 on s1.rowid >= s2.rowid
  group by s1.rowid
) final
group by grp

答案 1 :(得分:0)

这可能不是最好的解决方案(并且有一些边缘情况---如果你有一个不为null的3值),并且可能可以放入一个查询,但我需要RowId加入。不过应该这样做:

CREATE TEMP TABLE split1 (foo1 int);
CREATE TEMP TABLE split2 (foo2 int);
CREATE TEMP TABLE split3 (foo3 int);

INSERT INTO split1
SELECT foo FROM sample WHERE foo % 3 = 1 ORDER BY foo

INSERT INTO split2
SELECT foo FROM sample WHERE foo % 3 = 2 ORDER BY foo

INSERT INTO split3
SELECT foo FROM sample WHERE foo % 3 = 0 ORDER BY foo

SELECT 
    CASE 
        WHEN foo2 IS NULL THEN foo1
        WHEN foo3 IS NULL THEN foo1||','||foo2
        ELSE foo1||','||foo2||','||foo3
    END
FROM split1
    LEFT JOIN split2 
        ON split1.RowId = split2.RowId
    LEFT JOIN split3
        ON split2.RowId = split3.RowId