如何运行查询以根据条件将所需行转换为列

问题描述 投票:1回答:1

目前我有26个传感器设置为定期将数据记录到我的数据库。每隔10 ms,“Val”列添加了26个值,其旁边有相应的标记索引(参见下面的“当前表”)。我希望运行一个查询,将标记索引列为列,其值按时间排序(请参阅“所需转换”)。很容易将单个标记索引的所有值作为列并按时间顺序提取,但我想对多个索引执行此操作并将它们列在彼此旁边。任何帮助将不胜感激!!!!!!!

当前表:

**DateAndTime   TagIndex    Val**
DateAndTime 1   TagIndex 0  Val 1
DateAndTime 1   TagIndex 1  Val 2
DateAndTime 1   TagIndex 2  Val 3
      ……    ……  ……
DateAndTime 1   TagIndex n  Val n
DateAndTime 2   TagIndex 0  Val n+1
DateAndTime 2   TagIndex 1  Val n+2
DateAndTime 2   TagIndex 2  Val n+3
      ……    ……  ……
DateAndTime m   TagIndex n  Val m

期望的转型

**DateAndTime   TagIndex 0  TagIndex 1  TagIndex 2  ……. TagIndex n**
DateAndTime 1   Val 1   Val 2   Val 3   ……  Val n
DateAndTime 2   Val n+1 Val n+2 Val n+3 ……  Val 2
……  ……  ……  ……  ……  ……
DateAndTime m   ……  ……  ……  ……  Val m
sql sql-server
1个回答
0
投票

尝试动态数据透视表。 我不知道你的表名是什么,所以把你的表名放在YourTableName

DECLARE @DynamicPivotQuery AS NVARCHAR(MAX)
DECLARE @ColumnName AS NVARCHAR(MAX)

--Get distinct values of the PIVOT Column 
SELECT @ColumnName= ISNULL(@ColumnName + ',','') 
       + QUOTENAME(TagIndex)
FROM (SELECT DISTINCT TagIndex FROM YourTableName) AS TagIndex

--Prepare the PIVOT query using the dynamic 
SET @DynamicPivotQuery = 
  N'SELECT DateAndTime, ' + @ColumnName + '
    FROM YourTableName
    PIVOT(SUM(Val)
          FOR TagIndex IN (' + @ColumnName + ')) AS PVTTable'
--Execute the Dynamic Pivot Query
EXEC sp_executesql @DynamicPivotQuery
© www.soinside.com 2019 - 2024. All rights reserved.