Skip to content
Advertisement

Merging query from same table into different columns

I’m having an issue querying a table for some information. Basically the way data was stored in the table, for every customer, its information was stored vertically and so on for others.

In my case I want to display in separate columns for example only the 'Company' and 'StreetAddress' values from all their information for each CustomerId.

I tried joins, unions and pivots but my skills with sql are still limited. This is how the original table looks like:

enter image description here

Advertisement

Answer

You can pivot with conditional aggregation. If you want three columns in the resultset that contain the id of the customer, their company and street address, you can do:

select
    customerid,
    max(case when key = 'Company' then value end) company,
    max(case when key = 'StreetAddress' then value end) street_address
from mytable
group by customerid
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement