SQL Server Daynamic视图列数 [英] sql server daynamic view column count
本文介绍了SQL Server Daynamic视图列数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我必须编程一个sql过程来获得结果,结果将连接不同记录的所有字段,我所拥有的是一个视图,在此视图中记录的数量具有相同的ID,然后我必须返回此视图格式
I have to program a sql procedure to get a result, the result will concatenate all fields of the different records, what i have is a view, in this view number of records has the same ID then I have to return of this format
ID F
1 1
1 2
1 3
1 4
1 5
我可以重复的次数更多还是ID更少,所以f的数量必须和重复次数一样多
may i have more repetition or ID or less so the f''s must be as much I have repetitions
ID f1 f2 f3 f4 f5
1 1 2 3 4 5
推荐答案
尝试一下:
Try this:
DECLARE @cols NVARCHAR(200)
DECLARE @dt NVARCHAR(1000)
DECLARE @pt NVARCHAR(2000)
SET @cols = STUFF((SELECT DISTINCT '],[' + F
FROM YourDataBase
ORDER BY '],[' + F
FOR XML PATH('')),1,2,'') + ']'
SET @dt = 'SELECT * ' +
'FROM YourTable'
SET @pt = 'SELECT ID, ' + @cols + ' ' +
'FROM (' + @dt + ') AS DT ' +
'PIVOT(MAX(F) FOR(ID) IN (' + @cols + ')) AS PT ' +
'ORDER BY ID'
EXEC (@pt)
这篇关于SQL Server Daynamic视图列数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文