What's the best way to pivot (or un-pivot) the table below:
CREATE TABLE dbo.Sections(
SectionId varchar(50) NOT NULL (PK),
Description varchar(255),
SubSectionIdA varchar(50),
SubSectionIdB varchar(50),
SubSectionIdC varchar(50),
SubSectionIdD varchar(50),
SubSectionIdE varchar(50)
);
and turn it into a schema like so:
CREATE TABLE dbo.NormalizedSections(
SectionId varchar(50) NOT NULL (FK and part of PK),
Description varchar(255),
SubSectionId varchar(50) NOT NULL (other part of PK),
Order int
);
So the Sections
table can have sample data like so:
SectionId Description SubSectionIdA SubSectionIdB SubSectionIdC SubSectionIdD SubSectionIdE
--------------------------------------------------------------------------------------------------------------------------------------------------------
Sec-01A Special section NULL '' SubsectionA1 SubsectionA2 ''
Sec-02B Cheap seats CheapSeciton1 '' CheapSectionTop NULL LimitedView
Sec-01B VIP Special CourtsideSeatView NULL NULL NULL
This needs to be turned into this:
SectionId Description SubSectionId Order
-------------------------------------------------------------------------------
Sec-01A Special section SubsectionA1 1
Sec-01A Special section SubsectionA2 2
Sec-02B Cheap seats CheapSeciton1 1
Sec-02B Cheap seats CheapSectionTop 2
Sec-02B Cheap seats LimitedView 3
Sec-01B VIP Special 1
Sec-01B VIP CourtsideSeatView 2
Is there a quick way to do this and load it into a temp table with some fancy non-cursor T-SQL in SQL Server?
CodePudding user response:
If it's a one off job, try UNPIVOT to convert the SubSectionId..N columns into rows. Then add a ROW_NUMBER() to the result to generate the order numbers by section and subsection
-- Unpivot the table.
SELECT unpvt.SectionId
, unpvt.Description
, unpvt.SubSection
, ROW_NUMBER() OVER(PARTITION BY SectionId ORDER BY SubSection) AS RowOrder
FROM
( SELECT SectionId
, Description
, SubSectionIdA
, SubSectionIdB
, SubSectionIdC
, SubSectionIdD
, SubSectionIdE
FROM Sections
) p
UNPIVOT
(
SubSection FOR SubSectionId
IN (SubSectionIdA
, SubSectionIdB
, SubSectionIdC
, SubSectionIdD
, SubSectionIdE
)
)AS unpvt
WHERE ISNULL(SubSection, '') <> ''