Thread: SQL Query Syntax help

SQL Query Syntax help

From
"srikkanth"
Date:
Hi Team,

Can you please help me in writing the syntax for the below mentioned table.

Input : 
ID Col ACol BCol CCol DCol ECol F
1111aaaabbbbccccddddeeeeffff
2222bbbbccccddddeeeeffffaaaa
3333ccccddddeeeeffffaaaabbbb
4444ddddeeeeffffaaaabbbbcccc
5555eeeeffffaaaabbbbccccdddd
6666ffffaaaabbbbccccddddeeee
7777ccccddddeeeeffffaaaabbbb
8888ddddeeeeffffaaaabbbbcccc
9999ffffaaaabbbbccccddddeeee
 
Required Output :
ID Col NameCol Value
1111Col Aaaaa
1111Col Bbbbb
1111Col Ccccc
1111Col Ddddd
1111Col Eeeee
1111Col Fffff
2222Col Abbbb
2222Col Bcccc
2222Col Cdddd
2222Col Deeee
2222Col Effff
2222Col Faaaa
3333Col Acccc
3333Col Bdddd
3333Col Ceeee
3333Col Dffff
3333Col Eaaaa
3333Col Fbbbb

And so on for the 4444, 5555, 6666, 7777, 8888, 9999


Thanks,
Srikanth B

Re: SQL Query Syntax help

From
"Daniel Verite"
Date:
    srikkanth wrote:

> Can you please help me in writing the syntax for the below mentioned

This looks like an UNPIVOT operation.

Here's a generic method that does this without having to specify the
columns individually, with the help of json functions:

SELECT ID, key, value FROM
  (SELECT ID, row_to_json(t.*) AS line FROM PivotTableName t) AS r
JOIN LATERAL json_each_text(r.line) on (key <> 'ID');


Best regards,
--
Daniel Vérité
PostgreSQL-powered mailer: http://www.manitou-mail.org
Twitter: @DanielVerite



Re: SQL Query Syntax help

From
"Daniel Verite"
Date:
    srikkanth wrote:

> Can you please help me in writing the syntax for the below mentioned

This looks like an UNPIVOT operation.

Here's a generic method that does this without having to specify the
columns individually, with the help of json functions:

SELECT ID, key, value FROM
  (SELECT ID, row_to_json(t.*) AS line FROM PivotTableName t) AS r
JOIN LATERAL json_each_text(r.line) on (key <> 'ID');


Best regards,
--
Daniel Vérité
PostgreSQL-powered mailer: http://www.manitou-mail.org
Twitter: @DanielVerite



Re: SQL Query Syntax help

From
Geoff Winkless
Date:
On Wed, 22 Jan 2020 at 11:00, srikkanth <srikkanth16081991@rediffmail.com> wrote:
Can you please help me in writing the syntax for the below mentioned table.

Suggest looking at the crosstab function.

https://www.postgresql.org/docs/current/tablefunc.html

    crosstab(text source_sql, text category_sql)
    Produces a "pivot table" with the value columns specified by a second query

Geoff

Re: SQL Query Syntax help

From
Geoff Winkless
Date:
On Wed, 22 Jan 2020 at 11:00, srikkanth <srikkanth16081991@rediffmail.com> wrote:
Can you please help me in writing the syntax for the below mentioned table.

Suggest looking at the crosstab function.

https://www.postgresql.org/docs/current/tablefunc.html

    crosstab(text source_sql, text category_sql)
    Produces a "pivot table" with the value columns specified by a second query

Geoff