Lambda是一種匿名函數,不需要命名,可以作為參數傳遞給其他函數或方法。本文介紹Lambda函數的使用限制、文法和使用樣本。
限制
不支援子查詢,例如
x->2+(SELECT3)
。不支援彙總,例如
x -> max(y)
。
文法
文法形式是:參數列表 ->
運算式或代碼塊
參數列表:是指Lambda函數接收的參數,可以為空白或包含一個或多個參數。
->
:分隔參數列表和運算式或代碼塊。
使用樣本
樣本1:擷取數組列的平方值
SELECT numbers,transform(numbers, n -> n * n) as squared_numbers FROM ( VALUES (ARRAY(1, 2)),(ARRAY(3, 4)),(ARRAY(5, 6, 7)) ) AS t(numbers);
返回結果如下:
+------------+-----------------+ | numbers | squared_numbers | +------------+-----------------+ | [5,6,7] | [25,36,49] | | [3,4] | [9,16] | | [1,2] | [1,4] | +------------+-----------------+
樣本2:將數群組轉換為字串
SELECT transform(prices, n -> CAST(n AS STRING ) || '$') as price_tags FROM ( VALUES (ARRAY(100, 200)),(ARRAY(30, 4)) ) AS t(prices);
返回結果如下:
+------------+ | price_tags | +------------+ | ["30$","4$"] | | ["100$","200$"] | +------------+
樣本3:計算線性函數值
SELECT xvalues, a, b, transform(xvalues, x -> a * x + b) as linear_function_values FROM ( VALUES (ARRAY(1, 2), 10, 5),(ARRAY(3, 4), 4, 2) ) AS t(xvalues, a, b);
返回結果如下:
+------------+------------+------------+------------------------+ | xvalues | a | b | linear_function_values | +------------+------------+------------+------------------------+ | [3,4] | 4 | 2 | [14,18] | | [1,2] | 10 | 5 | [15,25] | +------------+------------+------------+------------------------+