13

我确信这是一种简单的技术,尽管到目前为止我找不到答案!

我有

TIMESTAMP           | POINTNAME | VALUE
2012-10-10 16:00:00   AHU01       20
2012-10-10 16:00:00   AHU02       25
2012-10-10 16:00:15   AHU01       26
2012-10-10 16:00:15   AHU02       35

等等...(大约 800 个点名)

对于许多点名,我不想在枢轴“FOR”(如下文给出的语法)定义的“IN”子句中列出每个点名,但可能想使用子查询。

所以我想要的是所有 POINTNAME 值作为具有 TIMESTAMP AND VALUE 列的列,所以我将获得一个 TIMESTAMP 值和每个 POINTNAME 的许多列,每个 POINTNAME PER TIMESTAMP 只有一个值,所以我不需要聚合有什么,所以还是选择 max 吧?

就像是:

SELECT [TIMESTAMP] FROM ( SELECT * FROM POINT_TABLE)
PIVOT( Max[Value] FOR [POINTNAME] IN (SELECT DISTINCT [POINTNAME] FROM POINT_TABLE)

会产生——

   TIMESTAMP              AHU01          AHU02
 2012-10-10 16:00:00        20             25
 2012-10-10 16:15:00        26             35

我意识到这可能不是那么简单,但希望你能得到我想要实现的目标?

枢轴语法:

SELECT <non-pivoted column>,
    [first pivoted column] AS <column name>,
    [second pivoted column] AS <column name>,
    ...
    [last pivoted column] AS <column name>
FROM
    (<SELECT query that produces the data>) 
    AS <alias for the source query>
PIVOT
(
    <aggregation function>(<column being aggregated>)
FOR 
[<column that contains the values that will become column headers>] 
    IN ( [first pivoted column], [second pivoted column],
    ... [last pivoted column])
) AS <alias for the pivot table>
<optional ORDER BY clause>;
4

1 回答 1

13

对于动态列数,您必须使用动态 SQL

declare
    @cols nvarchar(max),
    @stmt nvarchar(max)

select @cols = isnull(@cols + ', ', '') + '[' + T.POINTNAME + ']' from (select distinct POINTNAME from TABLE1) as T

select @stmt = '
    select *
    from TABLE1 as T
        pivot 
        (
            max(T.VALUE)
            for T.POINTNAME in (' + @cols + ')
        ) as P'

exec sp_executesql  @stmt = @stmt

SQL 提琴示例

于 2012-11-06T06:18:30.913 回答