Home > Software engineering >  How to select all the column values corresponding to duplicate values in different column of a table
How to select all the column values corresponding to duplicate values in different column of a table

Time:07-29

My table is something like this.

customer table

I want to get all the mean values corresponding to a particular customer ID. For eg:

{customer_id: [mean_value1,mean_value2,..]} - {7: ]1,2,3]}, {8: [4,5,6,7]}, {9:[8,9,10,5,11]}

I don't want to fetch all the table data and then loop on the columns, that will take lots of time. is there any Flask ORM or normal query to fetch this?

CodePudding user response:

No other easier way to get it than using group by(because you did not specified any database version so I give you an example using Postgres' s function);

select customer_id, STRING_AGG(mean_value, ',' order by mean_value) means
from mytable group by customer_id order by customer_id;

If you want you can parse it like:

select concat('{', customer_id, ': ', '[', STRING_AGG(mean_value, ',' order by mean_value), ']}') output
from mytable group by customer_id order by customer_id;
  • Related