简体   繁体   中英

How to transpose making columns distinct values with multiples lines for each column

I have a table that each line has a customer name and a GUID that is a code for an audience. I want to have a resulta that each column has the GUIDs for each customer.

Original table:

Customer        | Audience
                |
Customer A      | a4e7c9b7-c9d6-4698-8dc8-e0f2920f6bb7
Customer B      | 7a1d31b9-ecec-4c09-9eb9-cb10a8cc7d58
Customer A      | fa89f93d-ad7c-47ee-9a0c-598430c63c43
Customer C      | 0bc45f14-6c1b-48cf-a79e-a7cdc24deecc
Customer A      | 980b90cc-c923-46be-a180-bbbdf43169b2
Customer B      | 29d4806f-70fb-4b5f-9630-7314c32a536a

I need somethin like 'select Customer A, Customer B, Customer C ........ Audience FROM Table'

The result that I need is something like these:

在此处输入图片说明

It could work export everything to excel and manipulate there.

Thanks!

One option would be a pivot query with the use of ROW_NUMBER to assign arbitrary positions to each GUID, for each customer. We can do this with three separate CTEs, one for each of the three customers in your data set:

WITH cteA AS (
    SELECT *, ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) rn
    FROM yourTable
    WHERE Customer = 'Customer A'
),
cteB AS (
    SELECT *, ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) rn
    FROM yourTable
    WHERE Customer = 'Customer B'
),
cteC AS (
    SELECT *, ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) rn
    FROM yourTable
    WHERE Customer = 'Customer C'
)

SELECT
    a.Audience,
    b.Audience,
    c.Audience
FROM cteA a
FULL OUTER JOIN cteB b
    ON a.rn = b.rn
FULL OUTER JOIN cteC c
    ON a.rn = c.rn AND b.rn = c.rn;

在此处输入图片说明

Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM