Avatar of csehz
csehzFlag for Hungary

asked on 

SQL - Unpivot unknown number of columns to rows

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)

Open in new window


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

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

User generated image
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,
SQLMicrosoft SQL Server

Avatar of undefined
Last Comment
csehz
ASKER CERTIFIED SOLUTION
Avatar of Ryan Chong
Ryan Chong
Flag of Singapore image

Blurred text
THIS SOLUTION IS ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
Avatar of csehz
csehz
Flag of Hungary image

ASKER

Ryan thanks that works great
Microsoft SQL Server
Microsoft SQL Server

Microsoft SQL Server is a suite of relational database management system (RDBMS) products providing multi-user database access functionality.SQL Server is available in multiple versions, typically identified by release year, and versions are subdivided into editions to distinguish between product functionality. Component services include integration (SSIS), reporting (SSRS), analysis (SSAS), data quality, master data, T-SQL and performance tuning.

171K
Questions
--
Followers
--
Top Experts
Get a personalized solution from industry experts
Ask the experts
Read over 600 more reviews

TRUSTED BY

IBM logoIntel logoMicrosoft logoUbisoft logoSAP logo
Qualcomm logoCitrix Systems logoWorkday logoErnst & Young logo
High performer badgeUsers love us badge
LinkedIn logoFacebook logoX logoInstagram logoTikTok logoYouTube logo