복붙노트

[SQL] 오라클 문자열 집계

SQL

오라클 문자열 집계

이 같은 내 테이블 구조 모양, 나는이 분야에 대한 새로운입니다. 나는 그것이 나를 위해 복잡 기본 queries.But을 알고있다. 이렇게 저를 도와주세요.

테이블 구조

  Customer          Product         piriority
    10001           Main_product    1
    10001           Sub_product1    2
    10001           Sub_product2    2
    10001           Sub_product3    2
    10001           Sub_product4    2
    10002           Main_product    1
    10002           Sub_product1    2
    10002           Sub_product2    2

예상 출력 :

Customer        Main_Product    Sub_product
10001           Main_product    Sub_product1,Sub_product2,Sub_product3,Sub_product4
10002           Main_product    Sub_product1,Sub_product2

해결법

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

    1.거기에 "주요 제품"이다 결코 한 다른 시간 때 나는 우선 순위의 열은 1이 항상 있다고 가정하겠습니다. 각 고객은 하나의 "주"제품이 같은 데이터에서 또한 보인다. 나는이 사실이라고 가정하겠습니다. 그렇지 않은 경우에 당신은 제품 그룹을 구별하는 다른 열이 있어야합니다. 당신은 단순히 아래에이를 추가 할 수 있습니다.

    거기에 "주요 제품"이다 결코 한 다른 시간 때 나는 우선 순위의 열은 1이 항상 있다고 가정하겠습니다. 각 고객은 하나의 "주"제품이 같은 데이터에서 또한 보인다. 나는이 사실이라고 가정하겠습니다. 그렇지 않은 경우에 당신은 제품 그룹을 구별하는 다른 열이 있어야합니다. 당신은 단순히 아래에이를 추가 할 수 있습니다.

    다음과 같이 복잡 / 효율적인 대답은 할 수있다 :

    select customer
         , max(product) keep (dense_rank first order by priority) as main_product
         , listagg(case when priority = 2 then product end, ', ')
             within group (order by product) as sub_product
      from products
     group by customer
    

    SQL 바이올린

    고객 별, 제품의 열은 다음 우선 순위 순서로 첫 번째 제품을 얻을, 모든 고객이 주요 제품이 있다고 가정합니다. 우선도 2와 같이하여 값을 연결하는 문자열 연결 LISTAGG 함수 ()를 사용하여 여기서 두 번째 열은 걸린다.

    나는 높은 KEEP 절에 대한 롭 반 Wijk의 블로그 게시물을 추천 할 것입니다.

    보다 표준 SQL 솔루션은 다음과 같을 것이다 :

    select a.customer, a.product as main_product
         , listagg(b.product, ', ') within group (order by b.product) as sub_product
      from products a
      join products b
        on a.customer = b.customer
     where a.priority = 1
       and b.priority = 2
     group by a.customer, a.product
    

    즉, 일의 우선 순위가 모든 것을 찾을 당신이 행을 생성 한 후 2의 우선 순위가 모든 것을 얻을 그 집계하려면이 옵션을 사용합니다.

  2. ==============================

    2.이 시도,

    이 시도,

    select customer
         , (select Product from yourtablename where pirority = 1) AS Main_Product
         , (select wm_concat(Product) from yourTablename where pirority = 2 ) AS Sub_product      
      from yourtablename 
     group by customer 
    
  3. from https://stackoverflow.com/questions/17501418/oracle-string-aggregation by cc-by-sa and MIT license