【问题标题】:Unpivot multiple rows取消透视多行
【发布时间】:2021-03-19 03:39:26
【问题描述】:

我想同时取消透视 2 行,并保持每个字段与其上方/下方的字段相关联。

Current table format

1 2 3 4 5 6
unwanted unwanted unwanted unwanted unwanted unwanted
Point_ID Easting Northing Height Azimuth Inclination
NA metres metres metres degress degrees

Desired table format

col units
Point_ID NA
Easting metres
Northing metres
Height metres
Azimuth degrees
Inclination degrees

到目前为止,我有: SELECT col FROM table1 UNPIVOT ( col for cols in ([1], [2], [3], [4], [5], [6]) AS table1Unpivot

但这只是将所有内容放入 1 列,我不确定如何获得第二个所需的列。 col 名称(Point_ID、easting 等)可能会更改顺序,但始终具有一致的名称,并且始终位于其关联单位的正上方。

谁能告诉我最好的解决方法,谢谢!

架构:

`CREATE TABLE [dbo].[table1](
    [1] [nvarchar](99) NULL,
    [2] [nvarchar](99) NULL,
    [3] [nvarchar](99) NULL,
    [4] [nvarchar](99) NULL,
    [5] [nvarchar](99) NULL,
    [6] [nvarchar](99) NULL
) ON [PRIMARY]
GO
INSERT [dbo].[table1] ([1], [2], [3], [4], [5], [6]) VALUES (N'unwanted', N'unwanted', N'unwanted', N'unwanted', N'unwanted', N'unwanted')
GO
INSERT [dbo].[table1] ([1], [2], [3], [4], [5], [6]) VALUES (N'Point_ID', N'Easting', N'Northing', N'Height', N'Azimuth', N'Inclination')
GO
INSERT [dbo].[table1] ([1], [2], [3], [4], [5], [6]) VALUES (N'NA', N'metres', N'metres', N'metres', N'degrees', N'degrees')
GO
`

【问题讨论】:

  • 请向我们展示您的尝试。并将您的数据显示为格式化文本,而不是图像。
  • 如果您将一些示例数据作为 DDL+DML 放入,您将更容易为人们提供帮助。
  • 您当前的表没有意义:您如何知道哪一行用于col 值以及哪一行用于units?如您所见,@JohnCappelletti 的答案使用 ORDER BY (SELECT NULL),因为无法识别行
  • “cols”行始终位于“units”行的正上方——它是从外部不一致的文件中导入的,所以很遗憾我对此没有太多控制权。我可以在表格左侧插入一个额外的列作为“行标题”,即每行都会显示“col”或“units” - 如果这有帮助吗?

标签: sql sql-server tsql unpivot


【解决方案1】:

也许是一个带有条件聚合的 UNPIVOT

示例

 Select col  =max(case when rn=1 then value end)
       ,units=max(case when rn=2 then value end)
  From  (
            Select * 
             From (Select *
                          ,rn=row_number() over(order by (select null)) 
                     From YourTable 
                     Where [1]<>'unwanted' ) src
             UnPivot ( value for item in ([1], [2], [3], [4], [5], [6]) ) unpiv
        ) A
 Group by item

退货

col          units
Point_ID     NA
Easting      metres
Northing     metres
Height       metres
Azimuth      degress
Inclination  degrees

【讨论】:

  • over(order by (select null)) 可以返回任何值,你怎么知道rn 的值是正确的?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多