将多行的信息分组,但将同一列分组到一行

Group information at many rows but the same column to the one row

你能帮我解决这个问题吗?我有一个 table 记录测量数据以及与 ParentID 相关的信息。不幸的是,每个测量数据都写入一列(由前一列的值标识)。我想从该列中读取所有值并将其写入一行但不同的列中,以便每个测量都有一行。 TagID 和实例值的组合可以是 21。所以我需要在结果中有 21 列,一行中有值 (M1....M21)。 运行 在 SQL 服务器 2016 上。

来源table:

ParentID TagID Instance Data
AA 14 2010 117.42
AA 18 3020 0.345
AA 16 2010 1.1234
BB 17 2016 12.1234
BB 09 0 0.0123

请求table:

ParentID M1 M2 M3 M4 M5 M6
AA 117.42 1.1234 0.345
BB 0.0123 12.1234

空列可以是 0 或者 NULL。

编辑 - 中的另一列 来源table:

ParentID TagID Instance Data DataText
AA 14 2010 117.42
AA 18 3020 0.345
AA 12 1000 Text1
BB 11 1010 Text2
AA 16 2010 1.1234
BB 17 2016 12.1234
BB 09 0 0.0123

请求table:

ParentID M1 M2 M3 M4 M5 M6 Text
AA 117.42 1.1234 0.345 Text1
BB 0.0123 12.1234 Text2

您正在寻找如下 PIVOT 查询

select ParentID, [14-2010] [M1], [18-3020] [M2],[16-2010] [M3]
from
(
select 
 ParentID, 
 CAST(TagID as NVARCHAR) + "-" +CAST(Instance AS NVARCHAR) as pivotcol,
 Data
from your table )src
PIVOT( MAX(Data) FOR pivotcol in ([14-2010],[18-3020],[16-2010]))p

我特意上了M3。在您的用例中,您可以随意在子查询部分和顶部 select 部分的枢轴内添加 tagid 和实例的唯一组合。