如何在另一个表中以特定模式显示表的数据

时间:2016-07-27 05:20:52

标签: mysql sql-server

我有一个包含三列和500行的表。我需要在另一个表中以特定模式显示该表的数据。

Col1    Col2    Col3 

Item1   Item2   Item3 

Item4   Item5   Item6

输出以下列模式显示 -

item1 item2 item3

item2 item1 item3

item3 item1 item2

item4 item5 item6

item5 item4 item6

item6 item4 item5

2 个答案:

答案 0 :(得分:1)

由于SQL集是无序的,您可以尝试:

WITH Source AS
(
    SELECT * FROM (VALUES
    ('Item1', 'Item2', 'Item3'),
    ('Item4', 'Item5', 'Item6')) T(Col1, Col2, Col3)
)
SELECT Col1, Col2, Col3 FROM Source
UNION ALL
SELECT Col2, Col1, Col3 FROM Source
UNION ALL
SELECT Col3, Col1, Col2 FROM Source

如果您需要继续订购,请参阅以下查询:

WITH Source AS
(
    SELECT *, ROW_NUMBER() OVER (ORDER BY (SELECT 1)) GroupNumber FROM (VALUES
    ('Item1', 'Item2', 'Item3'),
    ('Item4', 'Item5', 'Item6')) T(Col1, Col2, Col3)
),Numbered AS
(
    SELECT GroupNumber, 1 SecondaryGroup, Col1, Col2, Col3 FROM Source
    UNION ALL
    SELECT GroupNumber, 2, Col2, Col1, Col3 FROM Source
    UNION ALL
    SELECT GroupNumber, 3, Col3, Col1, Col2 FROM Source
)
SELECT Col1, Col2, Col3 FROM Numbered ORDER BY GroupNumber, SecondaryGroup

答案 1 :(得分:0)

这解决了你的问题。

Create table #temp (one nvarchar(50),two nvarchar(50), three nvarchar(50))  -- Source Table 
Create table #temptarget (one nvarchar(50),two nvarchar(50), three nvarchar(50)) -- Target Table
Insert into #temp -- Insert into Source Table. already you have
values('item1','item2','item3')
Insert into #temp
values('item4','item5','item6')
Insert into #temp
values('item7','item8','item9')

Declare @RowCount AS INT
Declare @currRowIndex AS INT = 1 -- Current Row Index
select @RowCount = COUNT(*) from #temp --  No Of Rows

WHILE (@currRowIndex <= @RowCount)
BEGIN -- Insert into target table
Insert into #temptarget 
select t.one, t.two,t.three from
(select ROW_NUMBER()OVER(Order By one) AS RNo,* from #temp) t Where t.RNo = @currRowIndex
UNION
select t.two, t.one,t.three from
(select ROW_NUMBER()OVER(Order By one) AS RNo,* from #temp) t Where t.RNo = @currRowIndex
UNION
select t.three, t.one,t.two from
(select ROW_NUMBER()OVER(Order By one) AS RNo,* from #temp) t Where t.RNo = @currRowIndex
SET @currRowIndex +=1
END
SELECT * FROM #temptarget