Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List ids in group query

Tags:

I want to return a row for each cluster of data that has a unique amount, operation, months, and fee for a given id.

Table is as follows:

enter image description here

I can almost get what I want with

SELECT amount, operation, months, fee, plan_id FROM promo_discounts WHERE promo_id = 1 GROUP BY amount, operation, months, fee 

Which will get:

enter image description here

But notice it only returns one plan_id when I want it to return something like 1, 2, 3

Is this possible?

like image 578
Steve Robbins Avatar asked Dec 19 '11 20:12

Steve Robbins


People also ask

Why group by clause is used in SQL?

Group by is one of the most frequently used SQL clauses. It allows you to collapse a field into its distinct values. This clause is most often used with aggregations to show one value per grouped field or combination of fields. We can use an SQL group by and aggregates to collect multiple types of information.

What group by does in SQL?

The SQL GROUP BY Statement The GROUP BY statement groups rows that have the same values into summary rows, like "find the number of customers in each country". The GROUP BY statement is often used with aggregate functions ( COUNT() , MAX() , MIN() , SUM() , AVG() ) to group the result-set by one or more columns.


Video Answer


2 Answers

You could use GROUP_CONCAT

SELECT amount, operation, months, fee,      GROUP_CONCAT(DISTINCT plan_id SEPARATOR ',') AS plan_id FROM promo_discounts WHERE promo_id = 1 GROUP BY amount, operation, months, fee 

Beware though, that the default maximum length is 1024, so if you're doing this with a large table, you could have truncated values...

like image 83
ircmaxell Avatar answered Sep 20 '22 15:09

ircmaxell


Have a look at the group_concat() function.

SELECT *, GROUP_CONCAT(id SEPARATOR ",") AS grouped_ids FROM table

like image 22
Thorsten Avatar answered Sep 20 '22 15:09

Thorsten