Skip to content
Advertisement

sql; concatenate MIN(price) and MAX(price) into column?

I am working on an aws athena query like so:

SELECT 
    normalised_brand, 
    COUNT(DISTINCT merch1) merch1_distinct_count,
    COUNT(DISTINCT category_level_1) category_level_1_distinct_count,
    COUNT(*) product_distinct_count,
    MIN(effective_price) maxprice, 
    MAX(effective_price) minprice 
    -- CONCAT_WS(' - ', minprice, maxprice) price_range
    
FROM "db" 
WHERE product_gap = 'yes' AND store_name = 'petco'
group by normalised_brand

Which will give results like so:

enter image description here

Right now I have maxprice and minprice as two separate columns, but I want to combine them into one column “price range” which will have minprice and maxprice separated by a ” – ” string, so it would look something like this:

price_range
3.99 - 5.33
2.11 - 9.99
2.22 - 2.22

I tried doing this by adding CONCAT but wasn’t getting working results. Im very new to sql and am wondering how I could potentially create this price range column by combining the MAX() and MIN() results into a string value.

Also, I it possible to add logic to SQL so that if the price range is zero (like in the case of 2.22 – 2.22 where max price and minprice are identical) to just display a single value instead of a price range with identical max/min values?

this last part is a stretch goal, first im just trying to create the price_range column

Advertisement

Answer

Use concat()

SELECT 
    normalised_brand, 
    COUNT(DISTINCT merch1) merch1_distinct_count,
    COUNT(DISTINCT category_level_1) category_level_1_distinct_count,
    COUNT(*) product_distinct_count,
    MIN(effective_price) maxprice, 
    MAX(effective_price) minprice 
    concat(cast(MIN(effective_price) as varchar(10)),'-',cast(MAX(effective_price) as varchar(10)))
FROM "db" 
WHERE product_gap = 'yes' AND store_name = 'petco'
group by normalised_brand
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement