-- variable table
DROP TABLE IF EXISTS var;
CREATE temp TABLE var (	VALUE VARCHAR(1000) );
INSERT INTO var(VALUE) SELECT 'WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW';

-- select
WITH recursive
ints(num) AS 
(
	SELECT 1
	UNION ALL
	SELECT num+1
	FROM ints
	WHERE num+1 <= LENGTH((SELECT VALUE FROM var))
)
,
chars(num,chr,nextChr,isGroupEnd) AS
(
	SELECT tmp.*, CASE WHEN tmp.nextChr <> tmp.chr THEN 1 ELSE 0 END groupEnds
	FROM (
	SELECT num, 
		   SUBSTRING((SELECT VALUE FROM var), num, 1) chr,
		   (SELECT SUBSTRING((SELECT VALUE FROM var), num+1, 1)) nextChr
	FROM ints
	) tmp
)
SELECT (SELECT VALUE FROM var) plain_text, (
	SELECT string_agg(concat(CAST(maxNoWithinGroup AS VARCHAR(10)) , chr), '' ORDER BY num)
	FROM (
		SELECT *, MAX(noWithinGroup) OVER (partition BY chr, groupNo) maxNoWithinGroup
		FROM (
			SELECT	num, 
					chr, 
					groupNo, 
					ROW_NUMBER() OVER( partition BY chr, groupNo ORDER BY num) noWithinGroup
			FROM (
			SELECT *, (SELECT COUNT(*) 
					   FROM chars chars2 
					   WHERE chars2.isGroupEnd = 1 AND 
					   chars2.chr = chars.chr AND 
					   chars2.num < chars.num) groupNo 
			FROM chars
			) tmp
		) sub
	) final
	WHERE noWithinGroup = 1
	) Rle_Compressed