如何为SQL动态数据透视查询添加条件?

时间:2017-12-19 17:43:47

标签: sql sql-server

我有一个系统,它定期从多个来源收集数据,然后在一列中列出所有数据。我已成功转动它,以便每个源都有单独的列(请参阅下面的代码和输出)。

我的问题是:我可以在这段代码中添加where条件的方式/位置,以便我只从某一天开始提取数据(DateAndTime BETWEEN" time1"" time2" )然后通过增加时间来排序行?

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 dbo.FloatTable1) AS TagIndex
ORDER BY TagIndex

--Prepare the PIVOT query using the dynamic 
SET @DynamicPivotQuery = 
  N'SELECT DateAndTime, ' + @ColumnName + '
    FROM dbo.FloatTable1
    PIVOT(SUM(Val)
          FOR TagIndex IN (' + @ColumnName + ')) AS PVTTable'
--Execute the Dynamic Pivot Query
EXEC sp_executesql @DynamicPivotQuery

这输出以下内容:

**DateAndTime                    0                     1                    2**
2017-12-12 16:27:41.000 17.7175064086914    0.04730224609375    -0.154193878173828
2017-12-13 10:41:19.000 17.4271354675293    0.197725296020508   -0.000985145568847656
2017-12-16 22:05:15.000 -0.0419089868664742 0.0367603302001953  0.00866413116455078
2017-12-16 13:20:25.000 -0.0222898945212364 0.0417251586914063  0.00660228729248047
2017-12-14 13:15:27.000 17.1524677276611    0.158931732177734   -0.0414285659790039
2017-12-13 12:17:28.000 17.4389095306396    0.217489242553711   0.0163974761962891
2017-12-13 22:41:27.000 17.3408145904541    0.133147239685059   -0.062190055847168

1 个答案:

答案 0 :(得分:1)

添加如下的where子句:

--Prepare the PIVOT query using the dynamic 
SET @DynamicPivotQuery = 
  N'SELECT DateAndTime, ' + @ColumnName + '
    FROM dbo.FloatTable1
    PIVOT(SUM(Val)
          FOR TagIndex IN (' + @ColumnName + ')) AS PVTTable
WHERE DateAndTime BETWEEN ''VAL1'' AND ''VAL2'' ORDER BY DateAndTime'

HTH!