需求:现有一个逗号分隔的,由0和1 组成的字符串,要从这个字符串中找到0连续出现的最大次数。
要求:用SQL实现
字符串示例:‘0,1,0,0,1,1,0,0,0,0,0,1,0,0,1’
解题思路:
-- 在ClickHouse中的实现方式如下:
SELECT replace('0,1,0,0,1,1,0,0,0,0,0,1,0,0,1', ',', '') AS a1
┌─a1──────────────┐
│ 010011000001001 │
└─────────────────┘
SELECT splitByString('1', replace('0,1,0,0,1,1,0,0,0,0,0,1,0,0,1', ',', '')) AS a2
┌─a2────────────────────────────┐
│ ['0','00','','00000','00',''] │
└───────────────────────────────┘
SELECT arrayJoin(splitByString('1', replace('0,1,0,0,1,1,0,0,0,0,0,1,0,0,1', ',', ''))) AS a3
┌─a3────┐
│ 0 │
│ 00 │
│ │
│ 00000 │
│ 00 │
│ │
└───────┘
SELECT LENGTH(arrayJoin(splitByString('1', replace('0,1,0,0,1,1,0,0,0,0,0,1,0,0,1', ',', '')))) AS a4
┌─a4─┐
│ 1 │
│ 2 │
│ 0 │
│ 5 │
│ 2 │
│ 0 │
└────┘
SELECT max(LENGTH(arrayJoin(splitByString('1', replace('0,1,0,0,1,1,0,0,0,0,0,1,0,0,1', ',', ''))))) AS max_len_0
┌─max_len_0─┐
│ 5 │
└───────────┘
最近有个朋友经常提到他思考问题的方式。不断的迭代,需求最优解。顺着他的这个思路,尝试了另一种实现方式。
在此一并奉献出来。
感谢NYJ。
SELECT arrayMax(arrayMap(x -> LENGTH(x), splitByString('1', replace('0,1,0,0,1,1,0,0,0,0,0,1,0,0,1', ',', '')))) AS max_len_0
┌─max_len_0─┐
│ 5 │
└───────────┘