In SQL Server, it's just a simple UNPIVOT
. There's no need for the CASE
statement, as the original column name comes back in the UNPIVOT
. We're able to just pull the left 2 characters from the original column name. If you wanted it to be something other than a derivative of the column name, you would have to use a CASE
.
Look at the outermost select to see where those selected columns are coming from.
SELECT unpiv.MemberID, unpiv.Name, unpiv.theCode, left(codes,2) AS theType
FROM
(
SELECT MemberID, Name, N1Code, N2Code, N3Code
FROM t1
) AS src
UNPIVOT
(
theCode FOR codes IN (N1Code, N2Code, N3Code)
) AS unpiv;
For MySQL 5.x and lower, you can use a CROSS JOIN
and a couple of CASE
statements.
SELECT t1.MemberID, t1.Name
, CASE cj.colName
WHEN 'N1Code' then t1.N1Code
WHEN 'N2Code' then t1.N2Code
WHEN 'N3Code' then t1.N3Code
END AS theCode
, CASE cj.colName
WHEN 'N1Code' then 'N1'
WHEN 'N2Code' then 'N2'
WHEN 'N3Code' then 'N3'
END AS theType
FROM t1
CROSS JOIN
(
SELECT 'N1Code' AS colName
UNION ALL
SELECT 'N2Code'
UNION ALL
SELECT 'N3Code'
) cj