2

I am using SQL where I have column having values like

A B
X1 2 4 6 8 10
X2 2 33 44 56 78 98 675 891 11111
X3 2 4 672 234 2343 56331
X4 51 123 232 12 12333

I want a query to get the value from col B with col A which has max count of values. I.e output should be

x2  2 33 44 56 78 98 675 891 11111

Query I use:

select max(B) from table

Results in

51 123 232 12 12333
jarlh
  • 42,561
  • 8
  • 45
  • 63

2 Answers2

4

Assuming that both columns are strings, and that column B uses single space for separators and no leading/trailing spaces, you can use this approach:

SELECT A, B
FROM MyTable
ORDER BY DESC LENGTH(B)-LENGTH(REPLACE(B, ' ', ''))
FETCH FIRST 1 ROW ONLY

The heart of this solution is LENGTH(B)-LENGTH(REPLACE(B, ' ', '')) expression, which counts the number of spaces in the string B.

Note: FETCH FIRST N ROWS ONLY is Oracle-12c syntax. For earlier versions use ROWNUM approach described in this answer.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
1

In case there is more than one separating space or more then one row meets criteria do this: count number of spaces (or groups of spaces) in each row using regexp_count(). Use rank to find most (groups of) spaces. Take only rows ranked as 1:

demo

select *
  from (select t.*, rank() over (order by regexp_count(b, ' +') desc) rnk from t)
  where rnk = 1
Ponder Stibbons
  • 14,723
  • 2
  • 21
  • 24