Skip to content

Table tranformation for tabular output #723

Answered by lovasoa
beingalink asked this question in Q&A
Discussion options

You must be logged in to vote

Hello and welcome to SQLPage!

Indeed this is more of a SQL question than a SQLPage question, but I'm glad to answer it anyway :)

You can achieve the desired result using SQL's CASE statement in combination with GROUP BY.

Here’s the query you can use to transform your data into the desired format:

SELECT 
    city,
    year,
    MAX(CASE WHEN variable = 'var1' THEN value END) AS var1,
    MAX(CASE WHEN variable = 'var2' THEN value END) AS var2
FROM your_table
GROUP BY city, year
ORDER BY city, year;

You will need to know in advance the values var1 and var2.

Explanation

  1. CASE Statement:

CASE WHEN variable = 'var1' THEN value END: Selects the value for var1.

CASE WHEN variable = 'var2' THEN…

Replies: 2 comments

Comment options

You must be logged in to vote
0 replies
Answer selected by beingalink
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants