SQL Server:组合行

时间:2017-11-23 09:37:23

标签: sql sql-server

我有将四行(value3 = rowNumber)合并为一行的问题

我有类似的东西:

id  value1  value2  value3
 A1   11       21      1
 A2   12       22      2
 A3   13       23      3
 A4   14       24      4

我需要类似的东西

id  value1  value2  id  value1  value2  id value1  value2  id  value1 value2
 A1    11      21    A2     12     22    A3   13      23    A4    14     24

有人可以帮我解决这个问题吗?

3 个答案:

答案 0 :(得分:0)

试试这个,

CREATE TABLE #Table(Id varchar(5), value1 int, Value2 int,value3 int)
INSERT INTO #Table VALUES('A1',11,21,1)
INSERT INTO #Table VALUES('A2',12,22,2)
INSERT INTO #Table VALUES('A3',13,23,3)
INSERT INTO #Table VALUES('A4',14,24,4)


SELECT T1.Id,T1.value1,T1.Value2,T2.Id,T2.value1,T2.Value2,T3.Id,T3.value1,T3.Value2,T4.Id,T4.value1,T4.Value2
FROM #Table T1
INNER JOIN #Table T2 ON T1.value3=T2.value3-1
INNER JOIN #Table T3 ON T1.value3=T3.value3-2
INNER JOIN #Table T4 ON T1.value3=T4.value3-3

希望这会对你有所帮助。

答案 1 :(得分:0)

这个非常难看,但您可以尝试条件case聚合

SELECT MAX(CASE(ID) WHEN 'A1' THEN ID ELSE NULL END) [A1],
       MAX(CASE(ID) WHEN 'A1' THEN value1 ELSE NULL END) [value1],
       MIN(CASE(ID) WHEN 'A1' THEN value2 ELSE NULL END) [value2],
       ..
       ..
       MAX(CASE(ID) WHEN 'A4' THEN ID ELSE NULL END) [A4],
       MAX(CASE(ID) WHEN 'A4' THEN value1 ELSE NULL END) [value1],
       MIN(CASE(ID) WHEN 'A4' THEN value2 ELSE NULL END) [value2]

       FROM <table>

结果:

id  value1  value2  id  value1  value2  id value1  value2  id  value1 value2
 A1    11      21    A2     12     22    A3   13      23    A4    14     24

答案 2 :(得分:0)

尝试此代码以获得最佳解决方案,

                    DECLARE @table TABLE(ID VARCHAR(50),value1 VARCHAR(50),value2 VARCHAR(50),value3 VARCHAR(50))


        INSERT INTO @table ( ID, value1, value2, value3 )
        SELECT 'A1',11,21,1
        UNION
        SELECT 'A2',12,22,2
        UNION
        SELECT 'A3',13,23,3
        UNION
        SELECT 'A4',14,24,4





        SELECT Val, pvtCol INTO #table FROM(
        SELECT *,col+'_'+CONVERT(VARCHAR(50),ROW_NUMBER() OVER(ORDER BY (SELECT 1))) pvtCol   FROM
        @table  tbl
        UNPIVOT 
        ( val FOR col IN (ID,value1,value2))
        unPvt
        )x

        DECLARE @PvtCol NVARCHAR(MAX) = STUFF((SELECT ',[' + pvtCol,']' FROM #table FOR XML PATH('')),1,1,'')
        DECLARE @PvtColDisplay NVARCHAR(MAX) = STUFF((SELECT ',[' + pvtCol,'] AS [' + LEFT(pvtCol,CHARINDEX('_',pvtCol)-1),']' FROM #table FOR XML PATH('')),1,1,'')

        EXEC ('SELECT '+@PvtColDisplay+' FROM #table rdyPvt
        PIVOT 
        (
        MAX(Val) FOR pvtCol IN ('+@PvtCol+')
        ) pvt')



        DROP  TABLE #table