Question

I have a table where I have

Field1 | Field2 | Field3 | Low | High

I don't care about the Field3 breakdown so want to end up with one record for each Field 1 | Field 2 set with:

Field1 | Field2 | Low| High

(since I don't care about the Field 3 breakout)

and end up with e.g

  • Apple | White | 1 | 100
  • Banana | White | 101 | 400
  • Kiwi | white | 402 | 750
  • Banana | Black | 1 | 85
  • Apple | Black | 90 | 205
  • Kiwi | Black | 210 | 5504 etc

So I figured I could do

Create table LOW_HIGH_ALL as (select ID, FIeld1, FIeld2, max(High), min(Low) from LOW_HIGH group by Field1, Field2

As you can see each Field 1 represents a range in the Field B field that does not overlap the other.

The problem is there is some 'bad data' so sometimes I end up with:

  • Apple | White | 1 | 100
  • Banana | White | 1 | 400
  • Kiwi | white | 1 | 750

i.e. bad Min data. I can't just assume 1 is always bad. So I thought if I could get next to lowest Min I could get

  • Apple | White | 1 | 4 | 100
  • Banana| White | 1 | 101 | 400
  • Kiwi | White | 1 | 401 | 700

And can use the difference between 'Min-1' and Min to figure out when I have bad min data (and can use the second value instead, so far it seems to just be one bad min data occasionally.

I have tried to do Min-1 that doesn't work so wondering if there is some other way to extract the second lowest value.

Was it helpful?

Solution

Second lowest is a bit of a pain. But, you can do it in MySQL with the substring_index()/group_concat() trick:

Create table LOW_HIGH_ALL as 
    select ID, FIeld1, FIeld2, max(High), min(Low),
           substring_index(substring_index(group_concat(distinct low order by low asc), ',', 2), ',', -1) as min_2
    from LOW_HIGH
    group by Field1, Field2;

This concatenates the "low" values together and then extracts the second from the resulting string.

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