这里我的数据库中有两个名为Topic和Soltion的表。
我的表格如下所示。
主题表:
Topic
A
B
C
D
第二张表
Solution
AA
BB
CC
DD
EE
FF
GG
HH
II
JJ
KK
LL
MM
NN
OO
PP
这两个是我的表格,我希望将这两个表格转移到下面
Piviot table
A B C D
AA EE HH MM
BB FF JJ NN
CC GG KK OO
DD LL
请帮忙......
答案 0 :(得分:1)
因为这里没有逻辑,我创建了自己的:D(只是有兴趣自动执行此操作)。
我的逻辑是,我把第一个主题' A'来自Solution的4行,第二行' B'接下来的3行,第3行,依此类推。拆分解决方案分为4行和3行。
请查看示例中的评论:
-----------
--created some data to test
-----------
DECLARE @Topic TABLE (topic CHAR(1))
INSERT INTO @Topic SELECT 'A'
INSERT INTO @Topic SELECT 'B'
INSERT INTO @Topic SELECT 'C'
INSERT INTO @Topic SELECT 'D'
DECLARE @Solution TABLE (solution CHAR(2))
INSERT INTO @Solution SELECT 'AA'
INSERT INTO @Solution SELECT 'BB'
INSERT INTO @Solution SELECT 'CC'
INSERT INTO @Solution SELECT 'DD'
INSERT INTO @Solution SELECT 'EE'
INSERT INTO @Solution SELECT 'FF'
INSERT INTO @Solution SELECT 'GG'
INSERT INTO @Solution SELECT 'HH'
INSERT INTO @Solution SELECT 'II'
INSERT INTO @Solution SELECT 'JJ'
INSERT INTO @Solution SELECT 'KK'
INSERT INTO @Solution SELECT 'LL'
INSERT INTO @Solution SELECT 'MM'
INSERT INTO @Solution SELECT 'NN'
INSERT INTO @Solution SELECT 'OO'
INSERT INTO @Solution SELECT 'PP'
--DROP TABLE #topicCTE
-----------
--created table which shows what IDs from solution table must get topic
-----------
;WITH topicCTE As (
SELECT topic, ROW_NUMBER() OVER (ORDER BY topic) AS ID
FROM @Topic
)
SELECT topic, ID
, CASE WHEN ID % 2 = 1 THEN (((ID / 2)+1) *4 + (ID / 2) *3)-4 ELSE (((ID / 2)) *4 + (ID / 2) *3)-3 END AS RowsMINID
, CASE WHEN ID % 2 = 1 THEN (((ID / 2)+1) *4 + (ID / 2) *3) ELSE (((ID / 2)) *4 + (ID / 2) *3) END AS RowsMAXID
INTO #topicCTE
FROM topicCTE
/*Example Result
topic ID RowsMINID RowsMAXID
A 1 0 4
B 2 4 7
C 3 7 11
D 4 11 14
*/
--DROP TABLE #FinalData
-----------
--attached topics to solution
-----------
;WITH SolutionCTE AS (
SELECT Solution, ROW_NUMBER() OVER (ORDER BY Solution) AS ID
FROM @Solution
)
SELECT S.Solution, T2.Topic, ROW_NUMBER() OVER (PARTITION BY T2.Topic ORDER BY Solution) AS RowsID
INTO #FinalData
FROM SolutionCTE AS S
CROSS APPLY (
SELECT *
FROM #topicCTE AS T
WHERE T.RowsMINID < S.ID AND T.RowsMAXID >= S.ID
) AS T2
/*Example result
Solution Topic RowsID
AA A 1
BB A 2
CC A 3
DD A 4
EE B 1
FF B 2
GG B 3
*/
-----------
--get columns for pivot from @topic table
-----------
DECLARE @columns VARCHAR(1000) = STUFF((SELECT ',[' + topic + ']' FROM @Topic FOR XML PATH('')), 1, 1, '')
-----------
--create pivot sql command
-----------
DECLARE @sql NVARCHAR(MAX) = N'
SELECT ' + @columns + '
FROM #FinalData
PIVOT
(
MAX(Solution)
FOR [Topic] IN (' + @columns + ')
) AS p';
EXECUTE sp_executesql @sql
/*FINAL Results
A B C D
AA EE HH LL
BB FF II MM
CC GG JJ NN
DD KK
*/
我想这不是什么要求,但是很好的解决方案:D