简体   繁体   English

postgresql中其他列的不同和列表

[英]Distinct and List of other column in postgresql

I am using postgres DB and i have table with two column name and sal .我正在使用 postgres DB,我有两个列namesal的表。

   name       Sal
  Raunak     10000
  Raunak     5000
  Rahul      500
  Raunak     300

And i want而且我要

Raunak 10000,5000,300
Rahul  500

i am using JPA is there any way to get in JPA data我正在使用 JPA 有什么方法可以获取 JPA 数据

You can use string_agg function to build a comma separated list of values:您可以使用 string_agg 函数来构建一个逗号分隔的值列表:

select name, string_agg(sal::text, ',')
from t
group by name

You might want to consider json_agg instead of csv if your application can consume json data.如果您的应用程序可以使用 json 数据,您可能需要考虑json_agg而不是 csv。

If you want to preserve the data type of the sal column, you can use array_agg() that returns an array of values.如果要保留sal列的数据类型,可以使用返回值数组的array_agg() Not sure if JPA will let you access that properly though不确定JPA是否会让您正确访问它

select name, array_agg(sal) as sals
from the_table
group by name;

If I understand your question correctly, you want to get the result via below SQL statement:如果我正确理解您的问题,您希望通过以下 SQL 语句获得结果:

SELECT
  name,
  string_agg (sal::varchar(22), ', ') as sals
FROM
  test
GROUP BY
  name;

Since it's postgresql related SQL, we can't or hard to express it via common object query.由于是postgresql相关的SQL,我们不能或者很难通过普通对象查询来表达。 You can construct the above SQL via native query mode in your JPA code.您可以在 JPA 代码中通过本机查询模式构造上述 SQL。

@Query(value = "<the above query>", nativeQuery = true)
List<Object[]> query();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM