Question

I need to compare 2 strings that contains number and possibly text. for example I have this table:

id | label 1  |  label 2 | 
1  |  12/H    |     1    |
2  |   4/A    |    41/D  |
3  |  13/A    |     3/F  |
4  |   8/A    |     8/B  |
..

I need to determine the direction so that if Label 1 < Label2 then Direction is W (with) else it is A (against). So I have to build a view that presents data this way:

id | Direction  
1  |     A    |   
2  |     W    |
3  |     A    |
4  |     W    |
..

I'm using postgres 9.2.

Was it helpful?

Solution

WITH x AS (
   SELECT id
         ,split_part(label1, '/', 1)::int AS l1_nr
         ,split_part(label1, '/', 2)      AS l1_txt
         ,split_part(label2, '/', 1)::int AS l2_nr
         ,split_part(label2, '/', 2)      AS l2_txt
   FROM t
   )
SELECT id
      ,CASE WHEN (l1_nr, l1_txt) < (l2_nr, l2_txt)
       THEN 'W' ELSE 'A' END AS direction
FROM   x;

I split the two parts with split_part() and check with an ad-hoc row type to check which label is bigger.

The cases where both labels are equal or where either one is NULL have not been defined.

The CTE is not necessary, it's just to make it easier to read.

-> sqlfiddle

OTHER TIPS

You can try something like:

SELECT id, CASE WHEN regexp_replace(label_1,'[^0-9]','','g')::numeric <
                     regexp_replace(label_2,'[^0-9]','','g')::numeric
                THEN 'W'
                ELSE 'A'
           END
FROM table1

regexp_replace deletes all non numeric characters from the string ::numeric converts the string to numeric.

Details here: regexp_replace, pattern matching, CASE WHEN

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top