2011-09-21 11 views
0

여러 행을 하나의 행으로 결합하고 쉼표로 구분 된 값이 포함 된 열을 어떻게 만들 수 있습니까?쉼표로 구분 된 값이 포함 된 sql 열

예 : 원래 내에서 SQLResult 반환 것 대신에 내가 아래에 결과를 반환하고 싶은

select order_no, item_no, item_description 
from orders... 

order_no  item_no item_description 
1234   5  toaster 
1234   6  hair dryer 

같은 간단한 선택 스크립트를 사용하여 다음과 같은합니다 ( item_nos와 같은 순서로 나열된 item_description을 가지고?

order_no  item_nos item_descriptions 
1234   5, 6  toaster, hair dryer 

그리고이 같은 결과를 반환 할 수 있을까?

order_no item_nos_descriptions 
1234  5 - toaster, 6 - hair dryer 

그런데 SQL 2008을 사용하고 있습니다 ...

+3

그것은 끔찍한 디자인 냄새 ...

이 작업을 수행하는 다른 방법은 재귀 CTE와 함께,하지만 나는 위에서 할 것이라 생각합니다. 관계형 데이터베이스는 정규화되도록 설계되었습니다. –

+0

SQL의 맛? SQL Server, MySQL, Postgres, Oracle? –

+0

이것이 스키마가 아니라 프레젠테이션/보고서라고 생각합니다. –

답변

1

group_concat functio를 확인하십시오. n (docs)이다. 이 같은 것을 보일 것이다, 당신이 요청 된 두 번째 양식의 경우

order_no  item_nos item_descriptions 
1234   5, 6  toaster, hair dryer 

:

select 
    order_no, 
    group_concat(item_no ORDER BY item_nos ASC SEPARATOR ', ') as item_nos, 
    group_concat(item_description ORDER BY item_no ASC SEPARATOR ', ') 
    as item_descriptions 
from orders 
group by order_no 

이런 식으로 뭔가를 줄 것이다

select 
    order_no, 
    group_concat(concat(item_no,' - ',item_description 
    ORDER BY item_no ASC SEPARATOR ', ') 
    as item_nos_descriptions 
from orders 
group by order_no 
0

가능한 경우 @pst에 유의해야한다고 생각합니다.

즉, 대부분의 관계형 데이터베이스에는 정확히 이것을 수행하는 기능이 있습니다. MySQL에서는 group_concat입니다. 오라클에서는 wm_concat입니다. PostgreSQL에서는 string_agg입니다. 오히려 표준화되지 않았 음을 주목하십시오. 모든 데이터베이스가 다시 행 CSV에서 얻을 수있는 방법이

SELECT order_no, string_agg(item_description, ',') 
FROM orders 
INNER JOIN line_items ON line_item.order_id = order.id 
GROUP BY order_no; 

참고 :이 기능을 사용하려면

, 당신은 같은 것을 할 것입니다. 이것은 PostgreSQL이 할 수있는 것입니다. 나는 오라클이 그 일을 할 수있을 것이라고 기대하지만 체크하지는 않았으며, 나는 MySQL이 할 수 없다고 확신하지만 오해 될 수있다. 당신이 MySQL을 사용하는 경우

0

GROUP_CONCAT을 시도해보십시오

SELECT order_no, 
    GROUP_CONCAT(item_no ORDER BY item_no ASC SEPARATOR ','), 
    GROUP_CONCAT(item_description ORDER BY item_no ASC SEPARATOR ',') 
FROM Orders 
GROUP BY order_no 

을 이러한 방법으로 원래의 표준화 된 DB 스키마를 유지하고 여전히 다음과 같은 결과를 얻을 수 있습니다 :

order_no  item_nos item_descriptions 
1234   5, 6  toaster, hair dryer 
+0

안녕하세요, 저는 현재 SQL 2008을 실행 중이지만 오류 메시지가 계속 나타납니다 "키워드 'ORDER'근처에 구문이 잘못되었습니다." – HL8

0

MySQL을 위해 당신이 할 수있는을 :

SELECT order_no, 
    GROUP_CONCAT(CONCAT(item_no,' - ',item_description) ORDER BY item_no ASC SEPARATOR ', ') 
FROM Orders 
GROUP BY order_no 
2

SQL Server 2005 및 최대를 들어, 여기 년대 나는 재귀 적 CTE를 사용하지 않고 보통 그렇게한다.

DECLARE @T TABLE 
(
order_no int, 
item_no int, 
item_description nvarchar(50) 
) 


INSERT INTO @T VALUES (1234, 5, 'toaster') 
INSERT INTO @T VALUES (1234, 6, 'hair dryer') 

SELECT order_no, 
    STUFF(
     (
      SELECT ', ' + CAST(item_no AS VARCHAR) AS [text()] 
      FROM @T As MyItem 
      WHERE MyItem.order_no = MyTable.order_no 
      FOR XML PATH('') 
     ), 1, 2, '') AS item_nos, 
    STUFF(
     (
      SELECT ', ' + CAST(item_no AS VARCHAR) AS [text()] 
      FROM @T As MyItem 
      WHERE MyItem.order_no = MyTable.order_no 
      FOR XML PATH('') 
     ), 1, 2, '') AS item_descriptions 
FROM @T AS MyTable 
GROUP BY order_no 

이 수율 :

Result Set (1 item) 
order_no | item_nos | item_descriptions | 
1234  | 5, 6   | 5, 6 

물건은 문자열에서 ','마지막을 제거합니다.

관련 문제