如果我将输入调用为3,尝试返回底部3结果的总和。目前它返回的数据集不允许,我该如何解决?
代码看起来像
DELIMITER++
CREATE FUNCTION function1 (input INT) returns INT
BEGIN
DECLARE amount int;
SET amount = input;
SELECT SUM(T.C1*Y.C2)
FROM Table T, YTable Y
WHERE T.ID=Y.TID
ORDER BY T.C1*Y.C2 ASC
LIMIT amount;
END++
表T(C1,ID)具有值
(20,1), (50,2), (100,3), (110, 4)
YTable Y(C2,TID)具有值
(30, 1), (90, 2), (110, 3), (160,4)
预期输出为20 * 30 + 50 * 90 + 100 * 110 = 16100
答案 0 :(得分:0)
使用ROW_NUMBER()
确定哪些是最低结果。
WITH cte as (
SELECT T.C1*Y.C2 as total,
ROW_NUMBER() OVER (ORDER BY T.C1*Y.C2) as rn
FROM Table T
JOIN YTable Y
ON T.ID = Y.TID
)
SELECT SUM(total)
FROM cte
WHERE rn <= input
答案 1 :(得分:0)
使用CONCAT()
,prepare
和execute
构建查询。