SQL使用单个表将行数据转换为列
我正在尝试将数据库表行之一转换为列,并使用带游标的 PIVOT 函数,这里是 Sql:
DECLARE Cur CURSOR FOR
SELECT DISTINCT CounterId
FROM AllCounterIds
DECLARE @Temp NVARCHAR(MAX),
@AllCounterIds NVARCHAR(MAX),
@CounterIdQuery NVARCHAR(MAX)
SET @AllCounterIds = ''
OPEN Cur
-- Getting all the movies
FETCH NEXT FROM Cur INTO @Temp
WHILE @@FETCH_STATUS = 0
BEGIN
SET @AllCounterIds = @AllCounterIds + '[' + @Temp + '],'
FETCH NEXT FROM Cur INTO @Temp
END
CLOSE Cur
DEALLOCATE Cur
SET @AllCounterIds = SUBSTRING(@AllCounterIds, 0, LEN(@AllCounterIds))
SET @CounterIdQuery = 'SELECT DateTime, ' + @AllCounterIds + '
FROM
(SELECT Type, DateTime, Value, AllCounterIds.CounterId
FROM AllCounterIds
INNER JOIN AllCounters
ON AllCounterIds.CounterId = AllCounters.CounterId) S
PIVOT
(
SUM (Value)
FOR CounterId IN
(' + @AllCounterIds + ')) AS pvt'
EXEC sp_executesql @CounterIdQuery
其中 AllCounterIds 是我使用此创建的视图:
GO
CREATE VIEW AllCounterIds AS
SELECT DISTINCT CounterId FROM AllCounters
GO
所以问题是到目前为止我表中有大约 27993600 行,当我执行 SQL 时,需要大约 4 分钟和大约 15 秒才能给出输出,并且根据性能要求,它很糟糕......所以我的问题是,无论如何我都可以达到我想要的结果但获得更好的性能?
只是为了让您知道表上也定义了簇索引......
I am trying to convert one of DB table row in to column and using PIVOT function with cursors, here is the Sql:
DECLARE Cur CURSOR FOR
SELECT DISTINCT CounterId
FROM AllCounterIds
DECLARE @Temp NVARCHAR(MAX),
@AllCounterIds NVARCHAR(MAX),
@CounterIdQuery NVARCHAR(MAX)
SET @AllCounterIds = ''
OPEN Cur
-- Getting all the movies
FETCH NEXT FROM Cur INTO @Temp
WHILE @@FETCH_STATUS = 0
BEGIN
SET @AllCounterIds = @AllCounterIds + '[' + @Temp + '],'
FETCH NEXT FROM Cur INTO @Temp
END
CLOSE Cur
DEALLOCATE Cur
SET @AllCounterIds = SUBSTRING(@AllCounterIds, 0, LEN(@AllCounterIds))
SET @CounterIdQuery = 'SELECT DateTime, ' + @AllCounterIds + '
FROM
(SELECT Type, DateTime, Value, AllCounterIds.CounterId
FROM AllCounterIds
INNER JOIN AllCounters
ON AllCounterIds.CounterId = AllCounters.CounterId) S
PIVOT
(
SUM (Value)
FOR CounterId IN
(' + @AllCounterIds + ')) AS pvt'
EXEC sp_executesql @CounterIdQuery
where AllCounterIds is a View that I created using this:
GO
CREATE VIEW AllCounterIds AS
SELECT DISTINCT CounterId FROM AllCounters
GO
So problem is I have around 27993600 rows in table now by far, and when I execute the SQL it takes arount 4min and some 15 sec to give me the output and as per performance requirement its bad ... so my question is that, is there anyway where I can achieve my desired result but getting better performance?
And just to let you know cluster indexes are also defined on the table ...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不确定它对于您的情况实际上更快,但也许尝试这样的方法
使用
varchar
而不是nvarchar
是有意的。您不太可能需要整数列表的unicode,它会节省一些内存,从而可能节省时间。I'm not sure it's actually faster for your case, but perhaps try something like this
The use of
varchar
instead ofnvarchar
is deliberate. It's not likely that you need unicode for a list of integers and it will save some memory, thus possibly time.