SQL服务器将行与列组合

时间:2015-07-01 21:20:18

标签: sql-server

我在SQL服务器中将两行合并到单列时遇到了问题。这就是我想要做的事情,我的原始表就像这样

--------------------------------------------
| id   ||   D_code1  || D_code2  || Dcode3 |    
--------   ----------   --------   --------
| 1    ||   2f       || v012     || F013   |       
| 1    ||   k013     || c190     || NULL   |
--------------------------------------------

我希望它像这样加载。它有点复杂。

  ----------------------------------
  | id  ||  D_code                 |
   ----    ------------------------
  |  1  ||  2f,v012,F013,k013,c190 | 
  ----------------------------------

请有人帮我解决这个问题。我是sql server的新手。提前致谢。

3 个答案:

答案 0 :(得分:0)

你可以使用像那样的东西和xml

     SELECT   distinct  i.id AS [id],
        STUFF((    SELECT ',' + t.d_code1+' ,' +t.d_code2+' , '+t.d_code3 AS [text()]

                    FROM mytable t
                   WHERE
                   t.id = i.id
                    FOR XML PATH('') 
                    ), 1, 1, '' )


        AS [dcode]
     FROM mytable i

答案 1 :(得分:0)

严格意义上讲,如何实现结果,一个可能的答案就是自我联接。假设密钥是复合D_code1 / D_code2 / D_code3,则可以通过以下方式完成查询:

select t1.id,
isnull(t1.D_code1,'') + ',' +
isnull(t1.D_code2,'') + ',' +
isnull(t1.D_code3,'') + ',' +
isnull(t2.D_code1,'') + ',' +
isnull(t2.D_code2,'') + ',' +
isnull(t2.D_code3,'') as D_code
from t t1 
join t t2 on t1.id=t2.id 
and
isnull(t1.D_code1,'') + isnull(t1.D_code2,'') + isnull(t1.D_code3,'') 
<
isnull(t2.D_code1,'') + isnull(t2.D_code2,'') + isnull(t2.D_code3,'')

答案 2 :(得分:0)

您可以使用XML PathSTUFF功能来执行此操作:

;WITH mytable1
AS (
    SELECT id
        ,CONCAT (D_code1,',',D_code2,',',ISNULL(Dcode3, '')) AS D_Code
    FROM mytable
    )
SELECT DISTINCT id
    ,REPLACE(LTRIM(RTRIM(REPLACE(STUFF((
            SELECT ',' + D_Code  
            FROM mytable1 T1
            WHERE T1.id = T2.id
            FOR XML PATH('')
            ), 1, 1, ''),',',' '))),' ',',') AS D_Code 
          --couldn't remember how to remove the succeeding commas if it is blank, 
          --so used a replace and trim to do this
FROM mytable1 T2

SQL Fiddle Demo