Friday, March 1, 2024

Transpose a Table in SQL

 Write an SQL query to convert the given table in Table A to Table B



Table A



Table B 


Table A Query.

CREATE TABLE cupcake (

    customer_id varchar ,

    flavor VARCHAR(50),

    Qty INT

);


INSERT INTO cupcake (customer_id, flavor, Qty)

VALUES

    ('C1', 'Vanilla', 180),

    ('C1', 'Chocolate', 200),

    ('C1', 'Strawberry', 150),

('C2', 'Vanilla', 250),

    ('C2', 'Chocolate', 300),

    ('C2', 'Strawberry', 170);

select * from cupcake

Table A

Table B Query

select customer_id,

sum(case when flavor = 'Vanilla' then Qty else 0 end) as vanilla,

sum(case when flavor = 'Chocolate' then Qty else 0 end) as chocolate,

sum(case when flavor = 'Strawberry' then Qty else 0 end) as strawberry

from cupcake

group by customer_id;

Table B