[英]Pivoting a SQL Server table into a more normalized version
What's the best way to pivot (or un-pivot) the table below: pivot(或取消透视)下表的最佳方法是什么:
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:所以Sections
表可以有这样的示例数据:
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?在 SQL 服务器中,有没有一种快速的方法可以将其加载到带有一些花哨的非游标 T-SQL 的临时表中?
If it's a one off job, try UNPIVOT to convert the SubSectionId..N columns into rows.如果这是一次性工作,请尝试UNPIVOT将 SubSectionId..N 列转换为行。 Then add a ROW_NUMBER() to the result to generate the order numbers by section and subsection然后在结果中添加一个ROW_NUMBER()以按部分和小节生成订单号
-- 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, '') <> ''
Results:结果:
SectionId | Description | SubSection | RowOrder :-------- | :-------------- | :---------------- | -------: Sec-01A | Special section | SubsectionA1 | 1 Sec-01A | Special section | SubsectionA2 | 2 Sec-01B | VIP | CourtsideSeatView | 1 Sec-01B | VIP | Special | 2 Sec-02B | Cheap seats | CheapSeciton1 | 1 Sec-02B | Cheap seats | CheapSectionTop | 2 Sec-02B | Cheap seats | LimitedView | 3
See also db<>fiddle另见db<>fiddle
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.