MS SQL Server pivot table with subquery in column clause

本小妞迷上赌 提交于 2020-01-27 07:46:25

问题


Im sure this is a simple technique although I can't find an answer so far!

I have

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

etc... ( for approx 800 POINTNAMES)

with many pointnames I dont want to list each one in the 'IN' clause of the pivot 'FOR' (as syntax given below) definition but would like to use perhaps a subquery.

So what I would like is all the POINTNAME values as columns with A TIMESTAMP AND VALUE column, so I will get one TIMESTAMP value and many columns with each POINTNAME, there is only one value per POINTNAME PER TIMESTAMP so I don't need to aggregate anything so just choose max anyway?

Something like:

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

would produce-

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

I realise it is probably no this simple but hopefully you get what I'm trying to achieve?

PIVOT SYNTAX:

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>;

回答1:


for dynamic number of columns you have to use dynamic 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 FIDDLE EXAMPLE



来源:https://stackoverflow.com/questions/13245364/ms-sql-server-pivot-table-with-subquery-in-column-clause

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!