我正在使用postgresql。如何从第一桌到第二桌?谢谢
id | type | sum
-----+------+-----
1 | a | 100
2 | a | 200
3 | b | 500
t_sum | type | history
-------+------+---------------
300 | a | ['id' => 1, 'sum' => 100], ['id' => 2, 'sum' => 200]
500 | b | ['id' => 3, 'sum' => 500]
我试过这个,没有结果:
SELECT DISTINCT(a.type), SUM(a.sum) as t_sum, b.* as history FROM mytable a LEFT JOIN mytable b ON a.id = b.id GROUP BY a.type
答案 0 :(得分:3)
以下解决方案将最后一列作为json
数组返回:
SELECT sum(sum) AS t_sum,
type,
array_to_json(
array_agg(
json_build_object('id', id, 'sum', sum)
)
) history
FROM history
GROUP BY type
ORDER BY type;
┌───────┬──────┬───────────────────────────────────────────────────┐
│ t_sum │ type │ history │
├───────┼──────┼───────────────────────────────────────────────────┤
│ 300 │ a │ [{"id" : 1, "sum" : 100},{"id" : 2, "sum" : 200}] │
│ 500 │ b │ [{"id" : 3, "sum" : 500}] │
└───────┴──────┴───────────────────────────────────────────────────┘
(2 rows)