简体   繁体   中英

How to loop inside CASE with PostgreSQL?

In PostgreSQL's SQL, I have a column where the data comes in as an array. I need to loop through the array and categorize that row either as "No Pool", "Private Pool" or "Heated Pool".

What is the best way of accomplishing this?

    SELECT pool_features as PF, close_date as CD, close_price as CP, category as CAT
      FROM (SELECT close_date, close_price, pool_features,
            CASE 
            WHEN pool_features[0] = 'no_pool' THEN 'No Pool'
            WHEN pool_features[0] = 'private_pool' THEN 'Private Pool'
            WHEN pool_features[0] = 'heated_pool' THEN 'Heated Pool'
                        ELSE 'No Pool'
                        END AS category
            FROM dwellings.listings_oid
        ) as laundryData
    WHERE close_date > '2016-04-01' AND close_price IS NOT NULL AND close_price < 1000000000

Reading your question carefully, it looks like pool_features is an array and the first element contains the basic description of the pool. If this i not the case, please edit your question.

Fist, SQL arrays are math matrices, and they are 1-based. So you need to refer to the coordinates as 1 instead of 0.

Secondly, while that approach works, it breaks down if the array is unordered (but then you have 1NF issues too). If that is the case, think carefully about why you are doing what you are doing and redesign accordingly. However if it is still applicable (there are occasional reasons to break 1NF), then you can use the ANY() keyword. So instead of: pool_features[1] = 'no_pool' you would write it a 'no_pool' = ANY(pool_features)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM