我从临时表中选择数据:
CREATE TEMPORARY TABLE IF NOT EXISTS "tmp"
(
"fuel_type" TEXT,
"litres" NUMERIC(8,2),
"is_rent" BOOLEAN
);
insert into tmp values ('petrol', 10, False);
insert into tmp values ('petrol', 20, False);
insert into tmp values ('diesel', 20, False);
像这样:
SELECT
(SELECT row(fuel_type, SUM(litres))
FROM tmp
GROUP BY fuel_type);
如果
fuel_type
中有多个 tmp
,我会收到此错误:
SQL 错误 [21000]:错误:用作表达式的子查询返回多于一行
我期待这个输出
ARRAY_AGG
fuel_type|litres
petrol,40
diesel,20
您的查询的构建方式是问题所在。尝试下面的代码以获得预期的输出。
WITH FuelSums AS (
SELECT
fuel_type,
SUM(litres) AS total_litres
FROM
tmp2
GROUP BY
fuel_type
)
SELECT
STRING_AGG(CONCAT(fuel_type, ',', total_litres), '; ') AS fuel_data
FROM
FuelSums;