我有一个SQLite表
id name value
1 n1 v1
1 n2 v2
2 n1 v3
2 n2 v4
3 n1 v5
3 n2 v6
我希望得到如下表格
id n1 n2
1 v1 v2
2 v3 v4
3 v5 v6
我们可以在旧表中看到id不是唯一的,而转置后id在新表中是唯一的。 n的数量未知,但每个id应具有相同的n。
有没有办法通过SQLite查询获取转置表而无需创建新表?
答案 0 :(得分:1)
不幸的是,在单个查询的sqlite中无法做到这一点。您唯一能想到的就是用
之类的东西检索所有可能名称的列表SELECT DISTINCT name FROM t ORDER BY name
然后动态构造一个将产生所需结果的查询,例如以下(假设只有名称:n1
和n2
):
SELECT t0.id, t1.value AS n1, t2.value AS n2
FROM (SELECT DISTINCT id FROM t ORDER BY id) t0
LEFT JOIN t t1 ON t0.id=t1.id AND t1.name='n1'
LEFT JOIN t t2 ON t0.id=t2.id AND t2.name='n2';
或者,您可以使用相关子查询,但它可能会更慢:
SELECT
id,
(SELECT value FROM t WHERE id=t0.id AND name='n1') AS n1,
(SELECT value FROM t WHERE id=t0.id AND name='n2') AS n2
FROM (SELECT DISTINCT id FROM t ORDER BY id) t0;