SQLite如何水平堆叠组?

时间:2018-09-30 22:23:13

标签: sql sqlite

例如,说我有一张桌子(id是字母):

letter|color |number
a     |green |2
a     |blue  |3
b     |red   |3
b     |blue  |4
b     |yellow|1
c     |red   |9
c     |blue  |5

我想要的是将其转换为:

letter|color_1|color_2|color_3|number_1|number_2|number_3
a     |green  |blue   |       |2       |3       |
b     |red    |blue   |yellow |3       |4       |1
c     |red    |blue   |       |9       |5       |

这是什么类型的SQL转换?我的老板说这是经常做的事情,但我从未见过?另外,您会怎么做?

1 个答案:

答案 0 :(得分:2)

这是一个透视查询。如果您知道需要三组列,则可以使用条件聚合。

SQLite中的问题是您没有简单的枚举方法。为此,您可以使用子查询:

select t.letter,
       max(case when seqnum = 1 then color end) as color_1,
       max(case when seqnum = 2 then color end) as color_2,
       max(case when seqnum = 3 then color end) as color_3,
       max(case when seqnum = 1 then number end) as number_1,
       max(case when seqnum = 2 then number end) as number_2,
       max(case when seqnum = 3 then number end) as number_3
from (select t.*,
             (select count(*) from t t2 where t2.letter = t.letter and t2.color <= t.color) as seqnum
      from t
     ) t
group by t.letter;