Skip to content
Advertisement

Select Duplicate SKU’s and put corresponding prices into new adjacent columns

I have the following sql table – with duplicate SKU’s – each with differing prices which represent bulk buy discounts:

SKU Price
SKU1 $10.00
SKU2 $12.00
SKU2 $9.00
SKU1 $10.50
SKU2 $11.20

How can I use a SQL select statement to get the following output in the table below? Unique SKU’s with the prices in new columns – prices high to low in the price columns left to right:

SKU Price1 Price2 Price3
SKU1 $10.50 $10.00
SKU2 $12.00 $11.20 $9.00

My real-world data is for InCatalogue software which I use to bulk update prices in our printed catalogue in Adobe InDesign. The duplicate SKUs with differing prices represent bulk buy discounts. The InCatalogue software uses the identifier (SKU) to update tagged prices/text with the data from whichever column you specify it should look for (Price1, Price2 or Price3).

There is not always the same number of duplicate SKU’s – e.g. Some SKU’s don’t have any bulk buy discounts, hence there would only be a price in column “Price1”. Also, my real data actually has up to 4 duplicate SKU’s, and I also have to add GST/VAT inclusive prices into additional columns – however, this is simple and would/could be a simple table update after this transforming of data is done – unless this can simply be calculated at the same time? (Resulting in Price1 exGST, Price1 incGST, Price2 exGST, Price2 incGST etc)

Advertisement

Answer

If you know the maximum number of prices, you can use row_number() and conditional aggregation:

select sku,
       max(case when seqnum = 1 then price end) as price_1,
       max(case when seqnum = 2 then price end) as price_2,
       max(case when seqnum = 3 then price end) as price_3
from (select t.*,
             row_number() over (partition by sku order by price) as seqnum
      from t
     ) t
group by sku;

Note: This puts the prices in ascending order. It is not clear what ordering you might actually want, if any.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement