我正在使用SQL Server。我创建了一个查询,该查询将数据显示为:
accountNumber fundid
--------------------------
1 238492348 1004
2 238492348 1005
3 238492348 1006
4 238492348 1007
5 238492348 1008
6 238492348 1009
7 238492348 1022
8 238492348 1339
我正在尝试一些如何旋转表格以使表格看起来像这样:
accountNumber adv1 adv2 adv3 adv4 adv5 adv6 adv7 adv8
-----------------------------------------------------------------
1 238492348 1004 1005 1006 1007 1008 1009 1022 1339
有人可以协助我使用SQL Server做到这一点吗?
我正在阅读的所有内容都希望我像数字之和那样做或找到一个合计,但我只是想将其旋转并将其变成一行。它应具有的最多列数最多为adv25
。
任何帮助将不胜感激。
答案 0 :(得分:1)
这应该使您入门:
--DROP TABLE #tmpS
CREATE TABLE #tmpS (accountNumber VARCHAR(25), fundid int)
INSERT INTO #tmpS SELECT '238492348',1004
INSERT INTO #tmpS SELECT '238492348',1005
INSERT INTO #tmpS SELECT '238492348',1006
INSERT INTO #tmpS SELECT '238492348',1007
INSERT INTO #tmpS SELECT '238492348',1008
INSERT INTO #tmpS SELECT '238492348',1009
INSERT INTO #tmpS SELECT '238492348',1022
INSERT INTO #tmpS SELECT '238492348',1339
-- Consider adding more data here:
INSERT INTO #tmpS SELECT '240000000',1337
INSERT INTO #tmpS SELECT '240000000',1337
SELECT *
FROM
(SELECT ColNbr = ROW_NUMBER() OVER(PARTITION BY accountNUmber ORDER BY fundid,accountNumber)
,accountNumber
,fundid
FROM
#tmpS a
) src PIVOT(MAX(src.fundid) FOR src.ColNbr IN( [1]
,[2]
,[3]
,[4]
,[5]
,[6]
,[7]
,[8])) pvt