簡體   English   中英

如何將一張表中的幾行與另一張表中的每一行合並為單獨的列?

[英]How to combine several rows from one table with one row from another with each row a separate column?

我需要將一張表與另一張表中的多行合並到結果中的一行。 我的表是這樣設計的:

或類似。

有任何想法嗎? 給出的可用標簽數量有限(<10)。

我嘗試過的任何標准聯接都會給我幾行以得到具有相同customer_id的結果

表格1:

CUSTOMER_ID |  FIRSTNAME |  LASTNAME
1 |  ALICE |  MILLER
2 |  BOB |  SMITH

表2:

ID  |   CUSTOMER_ID |   TAG
1 |  1 |  PRO-CUSTOMER
2 |  1 |  ADMIN
3 |  2 |  PRO CUSTOMER
...

我需要像這樣的結果/視圖

ID |  FIRSTNAME |  LASTNAME |  TAG |  TAG
1 |  ALICE |  MILLER |  PRO CUSTOMER |  ADMIN
2 |  BOB |  SMITH |  PRO CUSTOMER | 

或類似...

SQL查詢具有一組固定的列。 您可以使用兩個標簽列來完成所需的操作:

select t1.customerid, t1.firstname, t1.lastname,
       min(t2.tag) as tag1,
       (case when min(t2.tag) <> max(t2.tag) then max(t2.tag)
        end) as tag2
from table1 t1 left join
     table2 t2
     on t1.customerid = t2.customerid
group by t1.customerid, t1.firstname, t1.lastname;

如果您只想要一個標簽列表-而不考慮其長度(最多4000個字符),則可以使用listagg()

select t1.customerid, t1.firstname, t1.lastname,
       listagg(t2.tag, ',') within group (order by t2.id) as tags
from table1 t1 left join
     table2 t2
     on t1.customerid = t2.customerid
group by t1.customerid, t1.firstname, t1.lastname;

使用ROW_NUMBER()分析函數為table2的每個標簽賦予每個客戶一個遞增的唯一編號,然后將輸出從行到列PIVOT ,然后將其連接到table1

Oracle安裝程序

CREATE TABLE table1 ( CUSTOMER_ID, FIRSTNAME, LASTNAME ) AS
  SELECT 1, 'ALICE', 'MILLER' FROM DUAL UNION ALL
  SELECT 2, 'BOB',   'SMITH' FROM DUAL;

CREATE TABLE table2 ( ID, CUSTOMER_ID, TAG ) AS 
  SELECT 1, 1, 'PRO-CUSTOMER' FROM DUAL UNION ALL
  SELECT 2, 1, 'ADMIN' FROM DUAL UNION ALL
  SELECT 3, 2, 'PRO CUSTOMER' FROM DUAL;

查詢

SELECT t1.customer_id,
       t1.firstname,
       t1.lastname,
       t2.tag1,
       t2.tag2,
       t2.tag3,
       t2.tag4  -- increase until you reach your maximum number of tags.
FROM   table1 t1
       LEFT OUTER JOIN
       (
         SELECT *
         FROM   ( SELECT customer_id, tag,
                         ROW_NUMBER() OVER ( PARTITION BY customer_id ORDER BY tag, id ) AS rn
                  FROM   table2 )
         PIVOT ( MAX( tag ) FOR rn IN (
           1 AS tag1,
           2 AS tag2,
           3 AS tag3,
           4 AS tag4 -- increase until you reach your maximum number of tags.
         )
       ) t2
       ON ( t1.customer_id = t2.customer_id );

輸出

CUSTOMER_ID | FIRSTNAME | LASTNAME | TAG1         | TAG2         | TAG3 | TAG4
----------: | :-------- | :------- | :----------- | :----------- | :--- | :---
          1 | ALICE     | MILLER   | ADMIN        | PRO-CUSTOMER | null | null
          2 | BOB       | SMITH    | PRO CUSTOMER | null         | null | null

db <> 在這里撥弄

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM