简体   繁体   中英

How to compare comma separated values across columns

I have a column where the values are comma separated combination of 2 other fields in a different table. The column looks like this:

col1    col2    col3
1   A,B 100
2   A,C 200
3   B,A 300
4   D,F 400
5   C,A 100
6   F,E 200
7   F,D 10000

When i aggregate at col2 level, I get A,B & B,A separately, the problem is A,B=B,A. How can i create a fourth column which simply flags such cases as either A,B or B,A . Either is fine as long as they are consistent.

This is likely to be a horrible data structure. You should not be storing values in a comma-delimited list. If you always have exactly two values, then you can use two columns. Or, you can use a junction/association table.

I would recommend splitting the values into two columns:

select t.*,
       least(substring_index(col2, ',', 1), substring_index(col2, ',', -1)) as col2_1,
       greatest(substring_index(col2, ',', 1), substring_index(col2, ',', -1)) as col2_2
from t;

The new columns, col2_1 and col2_2 are canonically ordered so reversing the original values doesn't matter.

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