我有一个显示如下数据的查询: -
t string_agg sid
'2010-04-17 00:00:00', 5.3000,4.3372,3.4000, 1
'2010-04-17 00:00:00', 5.3135,,3.0365,0.3795 2
我想显示如下数据: -
SELECT m.measurement_at AS t,MAX(CASE mc.type WHEN 'max' THEN VALUE END)
AS max_type,MAX(CASE mc.type WHEN 'mean' THEN VALUE END) AS mean_type,
MAX(CASE mc.type WHEN 'min' THEN VALUE END) AS min_type,MAX(CASE mc.type WHEN 'std' THEN VALUE END)
AS std_type,mc.sensor_id AS sId
FROM flow.measure m
INNER JOIN flow.measure_col mc
ON mc.id=m.measure_col_id
INNER JOIN flow.sensors s
ON s.id=mc.sensor_id WHERE s.station_id=1
GROUP BY t,sId ORDER BY t
我使用的查询:
const arrayToNestedObject = function(arr){
let start = '';
let end = '';
for(let i = 0; i < arr.length; i++){
start += '{"' + arr[i] + '":';
end += "}";
}
start += '""';
return JSON.parse(start + end);
}
答案 0 :(得分:1)
这是简单的字符串连接:
select t,
concat_ws(',', coalesce(max_type, ''), coalesce(mean_type, ''),
coalesce(min_type, ''), coalesce(std_type, '')
) as string_agg
sid
from . . . ;
你需要注意类型。上面假设这些值实际上是字符串(尽管它们很容易被转换成字符串)。
您可以将查询构造为:
SELECT m.measurement_at AS t,
concat_ws(',',
coalesce(MAX(CASE mc.type WHEN 'max' THEN VALUE END)::text, ''),
coalesce(MAX(CASE mc.type WHEN 'mean' THEN VALUE END)::text, ''),
coalesce(MAX(CASE mc.type WHEN 'min' THEN VALUE END)::text, ''),
coalesce(MAX(CASE mc.type WHEN 'std' THEN VALUE END)::text, '')
) as string_agg,
mc.sensor_id AS sId
FROM flow.measure m INNER JOIN
flow.measure_col mc
ON mc.id = m.measure_col_id INNER JOIN
flow.sensors s
ON s.id = mc.sensor_id
WHERE s.station_id = 1
GROUP BY t, sId
ORDER BY t;