sqlsql-serverpivot

How to split a column into 2 different columns with condition


I have this data about brands and sellers.

Brand BB_seller
Biotherm Amazon
BVLGARI 3rd Party
BVLGARI 3rd Party
Carolina Herrera Amazon
Chanel Amazon
Chanel Amazon
select Brand, substring([Buy Box Seller],1,9) as BB_seller
from italy_keepa
where [Buy Box Seller] is not null
order by Brand

I want to transform it into this type of table - so actually I just need to count different types of sellers

Brand Amazon 3rd party
Chanel 6 10

I tried this code - but numbers in count are strange

select Brand, count(distinct([Buy Box Seller])) as BB_seller
from italy_keepa
group by Brand
order by BB_seller desc
Brand BB_seller
Chanel 10
Tom Ford 3
Prada 3
Valentino 2

Solution

  • You need to use 'PIVOT` technique for this case. I just provide simple example of such query, and you can adopt it for you case:

    select 
        ProductCategoryID,
        count(case when Color  = 'Black' then ProductID end) balack_count,
        count(case when Color  != 'Black' then ProductID end) other_count
    from product
    group by ProductCategoryID 
    

    Try it online