Reputation: 35
I'm new to clickhouse or for that matter in any columnar db. I need to pivot the table like we do in sql-server, postgres or any other row based db.
I'm looking for a generic solution however solution to the example here will do well.
Table: Store
Tag Slot Reading
--- ---- --------
A 1 5
B 1 6
C 1 1
A 2 2
B 2 8
C 3 2
.
.
millions of rows
Transpose to:
Slot A B C and so on
--- -- -- --
1 5 6 1
2 2 8 -
3 - - 2
.
.
and so on
tags can be anywhere between 100 to 1000, slots can be between 1000-10000. But it doesn't matter.
I need to do this using sql only.
Thanks.
Upvotes: 2
Views: 7253
Reputation: 13310
create table xxx (Tag String, Slot Int64, Reading Int64) Engine=Memory;
insert into xxx values
('A',1,5),
('B',1,6),
('C',1,1),
('A',2,2),
('B',2,8),
('C',3,2)
SELECT
Slot,
groupArray((Tag, Reading))
FROM xxx
GROUP BY Slot
┌─Slot─┬─groupArray(tuple(Tag, Reading))─┐
│ 3 │ [('C',2)] │
│ 2 │ [('A',2),('B',8)] │
│ 1 │ [('A',5),('B',6),('C',1)] │
└──────┴─────────────────────────────────┘
Upvotes: 3
Reputation: 13310
select Slot,
sumIf(Reading, Tag='A') A,
sumIf(Reading, Tag='B') B,
...
group by Slot
select Slot, arrayReduce('sumMap', [(groupArray(tuple(Tag,Reading)) as a).1], [a.2])
...
group by Slot
select Slot, groupArray(tuple(Tag, Reading))
from
(select Slot, Tag, sum(Reading) Reading
...
group by Slot, Tag)
group by Slot
Upvotes: 0