This article is half-done without your Comment! *** Please share your thoughts via Comment ***
In this post, I am sharing a new feature CROSSTABVIEW in PSQL of PostgreSQL 9.6. Many times we require data arrangement horizontally, instead of vertically.
Something like we are doing in a spreadsheet where one element has a multiple child elements and require calculation horizontally for each group of items.
Now, you can use CROSSTABVIEW in new PSQL for this kind of requirement.
Below is a small demonstration of this:
Open a psql command line and create a below sample table:
1 2 3 4 5 6 |
create table tbl_range as select ('{a,b,c,d,e,f}'::text[])[1 + floor(random() * 6)] as data1 ,('{g,h,i,j,k,l}'::text[])[1 + floor(random() * 6)] as data2 ,random() * 1000 as randomnumber from generate_series(1,10000); |
Execute below few SELECTs:
1 2 |
select * from tbl_range; select data1, data2, count(*) from tbl_range group by data1, data2; |
Now check sample SELECT with CROSSTABVIEW:
1 |
select data1, data2, count(*) from tbl_range group by data1, data2 \crosstabview data1 data2 count; |
The result:
1 2 3 4 5 6 7 8 9 10 |
dbrnd=# select data1, data2, count(*) from tbl_range group by data1, data2 \crosstabview data1 data2 count; data1 | k | j | i | h | g | l -------+-----+-----+-----+-----+-----+----- f | 281 | 273 | 261 | 265 | 268 | 258 a | 288 | 293 | 278 | 293 | 248 | 279 d | 293 | 264 | 278 | 258 | 289 | 291 c | 272 | 276 | 292 | 287 | 263 | 281 e | 269 | 279 | 281 | 257 | 274 | 318 b | 289 | 270 | 301 | 295 | 247 | 291 (6 rows) |
Leave a Reply