복붙노트

[SQL] ID 값에 기초하여 연결할

SQL

ID 값에 기초하여 연결할

나는 테이블라는 결과와 같은 데이터 외모를 가지고 :

Response_ID    Label
12147          It was not clear
12458          Did not Undersstand
12458          Was not resolved
12458          Did not communicate
12586          Spoke too fast
12587          Too slow

이제 연결된 콤마에 의해 분리되는 출력 한 ID 당 행과 라벨의 값을 표시 할

내 출력은 다음과 같은 모양입니다 :

Response_ID    Label
12147          It was not clear
12458          Did not Undersstand,Was not resolved,Did not communicate
12586          Spoke too fast
12587          Too Slow

나는이 작업을 수행 할 수있는 방법 :

해결법

  1. ==============================

    1.당신은 하위 쿼리 문에 의해 순서없이 연결된 문자열의 순서에 대해 확신 할 수 없다. .value ( '.', 'VARCHAR (최대)') 부분은 라벨 및 같은 XML-쌀쌀 문자를 포함하는 경우가 처리하는 것입니다.

    당신은 하위 쿼리 문에 의해 순서없이 연결된 문자열의 순서에 대해 확신 할 수 없다. .value ( '.', 'VARCHAR (최대)') 부분은 라벨 및 같은 XML-쌀쌀 문자를 포함하는 경우가 처리하는 것입니다.

    declare @T table(Response_ID int, Label varchar(50))
    insert into @T values
    (12147,          'It was not clear'),
    (12458,          'Did not Undersstand'),
    (12458,          'Was not resolved'),
    (12458,          'Did not communicate'),
    (12586,          'Spoke too fast'),
    (12587,          'Too slow')
    
    select T1.Response_ID,
           stuff((select ','+T2.Label
                  from @T as T2
                  where T1.Response_ID = T2.Response_ID
                  for xml path(''), type).value('.', 'varchar(max)'), 1, 1, '') as Label
    from @T as T1
    group by T1.Response_ID
    
  2. ==============================

    2.아래 링크를 확인, 많은 다른 솔루션으로 문제를 접근

    아래 링크를 확인, 많은 다른 솔루션으로 문제를 접근

    http://www.simple-talk.com/sql/t-sql-programming/concatenating-row-values-in-transact-sql/

  3. ==============================

    3.

    DECLARE @Results TABLE(Response_ID INT, Label VARCHAR(80));
    
    INSERT @Results(Response_ID, Label)
    SELECT 12147,'It was not clear'
    UNION SELECT 12458,'Did not Undersstand'
    UNION SELECT 12458,'Was not resolved'
    UNION SELECT 12458,'Did not communicate'
    UNION SELECT 12586,'Spoke too fast'
    UNION SELECT 12587,'Too slow';
    
    WITH x AS 
    (
      SELECT Response_ID FROM @Results 
      GROUP BY Response_ID
    )
    SELECT x.Response_ID, Label = STUFF((SELECT ',' + Label
        FROM @Results WHERE Response_ID = x.Response_ID
        FOR XML PATH('')), 1, 1, '')
        FROM x;
    
  4. ==============================

    4.아주 성능이 좋은 것입니다, 이것을 고려 :

    아주 성능이 좋은 것입니다, 이것을 고려 :

    http://jerrytech.blogspot.com/2010/04/tsql-concatenate-strings-1-2-3-and.html

    그들은 성능이 좋은하지 않기 때문에 XML 기능을하지 마십시오.

    이 구현하는 몇 가지 노력을하지만, 수백만 행의 => 밀리 초 실행합니다.

  5. from https://stackoverflow.com/questions/6603319/concatenate-values-based-on-id by cc-by-sa and MIT license