虎克的博客

Enthusiasm Biogeography-Biodiversity Informatics-Data Sciences

合并多行数据到一行:合并异名记录到接受名的Synsum字段

| Comments

原来的数据表的格式及需求如下:

2009-05-25_00078

 

-- SQL2005 新的解决方法 -- 示例数据
DECLARE @t TABLE
    (
      id INT,
      value VARCHAR(300)
    )
INSERT  @t
        SELECT  synof,
                AbbreviateName
        FROM    dbo.Species
        WHERE   synof > 0    
-- 查询处理
SELECT  *
FROM    ( SELECT DISTINCT
                    id
          FROM      @t
        ) A
        OUTER APPLY ( SELECT    [values] = STUFF(REPLACE(REPLACE(( SELECT   value
                                                                   FROM     @t N
                                                                   WHERE    id = A.id
                                                                 FOR
                                                                   XML AUTO
                                                                 ), '<N value="', ','),
                                                         '"/>', ''), 1, 1, '')
                    ) N                    
                    
运行结果
2009-05-25_00079 

Comments