troubleshooting Question

SQL - Unpivot unknown number of columns to rows

Avatar of csehz
csehzFlag for Hungary asked on
SQLMicrosoft SQL Server
2 Comments1 Solution9 ViewsLast Modified:
Dear Experts,

Could you please have a look on the below short example (it can be reproduced by creating the below temp table and inserting those values),

CREATE TABLE
   #TempTable (
      CountryCode nvarchar(2),
      CountryName nvarchar(20),
      SearchTerm int,
      TaxNumber int,
      VAT int
      );

INSERT INTO
   #TempTable (CountryCode, CountryName, SearchTerm, TaxNumber, VAT)
VALUES
   ('AD', 'Andorra', 2, 3, 6),
   ('AL', 'Albania', 22, 32, 6),
   ('AM', 'Armenia', 24, 3, 66),
   ('AO', 'Angola', 11, 5, 9)

which per its logic being as a summary by countries, counting SAP fields filled for them:


Could you please advise which SQL code (Microsoft SQL Server) would be able to unpivot that table in the following format?


Briefly the target would be that the columns (SearchTerm, TaxNumber, VAT) with numbers should become rows, also would like to mention that searching for a dynamic solution as there are more than 150 columns are in the live environment

Thanks in advance,
ASKER CERTIFIED SOLUTION
Join our community to see this answer!
Unlock 1 Answer and 2 Comments.
Start Free Trial
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 2 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros