Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/76.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
SQL如何通过联接获取数组的select属性?_Sql_Postgresql_Join - Fatal编程技术网

SQL如何通过联接获取数组的select属性?

SQL如何通过联接获取数组的select属性?,sql,postgresql,join,Sql,Postgresql,Join,我正在使用postgresql。如何从第一张桌子到第二张桌子?多谢各位 id | type | sum -----+------+----- 1 | a | 100 2 | a | 200 3 | b | 500 t_sum | type | history -------+------+--------------- 300 | a | ['id' => 1, 'sum' => 100]

我正在使用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]
我试过这个,没有结果:


选择DISTINCT(a.type),SUM(a.SUM)作为t_SUM,b.*作为mytable a的历史记录按a.type左键连接a.id=b.id组上的mytable b
以下解决方案将最后一列作为
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)

DISTINCT
不是一个函数,它是
SELECT DISTINCT
的一部分,在整个选定行中工作。反正不需要,因为GROUP BY没有返回重复项。您使用的是MySQL还是Postgresql?回答很好,我刚刚在Postgres上检查了这个问题,它很有效。谢谢。为什么简单数组不工作,只有json格式?当然,你可以使用一个简单的数组,这只是一个例子。但是在这种情况下,
['id'=>1,'sum'=>100]
应该是什么数据类型呢?老实说,我不知道Postgresql返回什么数据类型。我猜像
数组这样的简单数组([1]=>['id'=>1,'sum'=>100],[2]=>['id'=>2,'sum'=>200])
是的,但是
['id'=>1,'sum'=>100]是什么?一根绳子?价值观?我决定使用JSON,但是如果你告诉我你需要什么,我可以修改答案。