gpt4 book ai didi

sql - MS SQL Server 数据透视表,列子句中带有子查询

转载 作者:行者123 更新时间:2023-12-02 10:12:54 30 4
gpt4 key购买 nike

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

我有

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 个 POINTNAMES)

对于许多点名,我不想在主元“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>;

最佳答案

对于动态列数,您必须使用动态 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

关于sql - MS SQL Server 数据透视表,列子句中带有子查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13245364/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com