How to pivot a table from an unpivot table

Hello,

I have unpivot table that I have created but now I would like to pivot it so the column answer is creating the columns. I have am struggling to even remember how to go about doing this… could be too late for brain to function.

Here is the unpivot code:

INSERT INTO QuestionCount
	(Village
	, Neighbourhood
	, Question
	, AnswerCount
	, Year)
SELECT CONCAT(Village,Setting) AS Village
	, Neighbourhood
	, 'I can be alone when I wish' AS Question
	, COUNT(CASE WHEN CanbealonewhenIwish IN (0.00)
			THEN 1
			ELSE NULL END) AS AnswerCount
	, Year
FROM Resident_Survey
GROUP BY Village, Neighbourhood, Setting, Year

Any help would be greatly apricated.

Thanks

Jes

Your code will be much easier to read if you format it. I have done it for you this time. To do it, either highlight the code and select the </> icon above the edit area, or place three backticks (`) on the line before your code, and three backticks on the line after your code. On most keyboards, you will find the backtick on the left-hand side of the top row of keys.

So instead of picking on my code are you going to answer my question?

I’m sorry. I wasn’t picking on your code. I was formatting it for this forum so that people could read it more easily and have an easier time answering your question. And explaining to you how to do it so that you could format any of your code that you wish to post in the future. Just trying to help.

3 Likes

pivoting can be accomplished with the PIVOT operator

you neglected to tell us which database system you’re running, so that’s as far as i want to take this solution for the time being

I am using SQL Sever 2016

well, you’re in luck then – FROM - Using PIVOT and UNPIVOT

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.