Search code examples
sqlexceladodb

Select distinct values one column into multiple columns


I have the following data: column 1 with many category and column 2 with values for each category. I need to convert or pivot this information to show each value for category group across multiple columns.

col1      col2
----------------
1         a    
2         b 
2         c
2         d
3         e
3         f 
4         g
4         h

And need this result:

col1      col2     col3     col4   col5   col6   
-----------------------------------------------   
1         a
2         b         c       d
3         e         f 
4         g         h

There are no more than seven values per tb1 count(column 2) group(column 1). All values from tb1 column 2 are different and about + 50 records.


Solution

  • You want to pivot your table, but your table doesn't currently contain the field that you want to pivot on ("col1", "col2", "col3", etc...). You need a row number, partitioned by col1. The Jet database does not provide a ROW_NUMBER function, so you have to fake it by joining the table to itself:

    select t1.col1, t1.col2, count(*) as row_num
    from [Sheet1$] t1
    inner join [Sheet1$] t2 on t2.col1 = t1.col1 and t2.col2 <= t1.col2
    group by t1.col1, t1.col2
    

    Now you can pivot on row_num:

    transform Min(x.col2) select x.col1
    from(
        select t1.col1, t1.col2, count(*) as row_num
        from [Sheet1$] t1
        inner join [Sheet1$] t2 on t2.col1 = t1.col1 and t2.col2 <= t1.col2
        group by t1.col1, t1.col2
        )  x
    group by x.col1
    pivot x.row_num