Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use sum() within a group_concat()?

Question revised

Really wanted a group_concat of sums...

Table: shops

+---------+--------+--------+
| shop_id | name   | state  |
+---------+--------+--------+
|    0    | shop 0 |    5   |
|    1    | shop 1 |    5   |
|    2    | shop 2 |    5   |
|    3    | shop 3 |    2   |
+---------+--------+--------+

Table: items

+------------+--------------+
|   shop  | item | quantity | 
+------------+--------------+
|    0    |  0   |    1     |
|    0    |  1   |    2     |
|    0    |  2   |    3     |
|    1    |  0   |    1     |
|    1    |  1   |    2     |
|    1    |  2   |    3     |
|    2    |  0   |    1     |
|    2    |  1   |    2     |
|    2    |  2   |    3     |
|    3    |  0   |    1     |
|    3    |  1   |    2     |
|    3    |  2   |    3     |
+------------+--------------+

    SELECT state,SUM(i.quantity) total
    FROM shops s2
    LEFT JOIN items i ON i.shop=s2.shopid
    WHERE state=5
    GROUP by item

result #1:

+--------+---------+
| state  |  total  |
+--------+---------+
|    5   |    3    |
+--------+---------+
|    5   |    6    |
+--------+---------+
|    5   |    9    |
+--------+---------+

But I would like the totals, like this:
result #2:
+--------+---------+---------+----------+
| state  | total 0 | total 1 |  total 2 |
+--------+---------+---------+----------+
|    5   |    3    |     6   |    9     |
+--------+---------+---------+----------+

or using group_concat()
result #3

+--------+---------+
| state  | totals  |
+--------+---------+
|    5   |  3,6,9  |
+--------+---------+

I cannot seem to get group_concat to grab the total column in result #1

Thanks in advance

like image 894
Mahks Avatar asked Feb 09 '10 10:02

Mahks


People also ask

What is the use of Group_concat in MySQL?

The GROUP_CONCAT() function in MySQL is used to concatenate data from multiple rows into one field. This is an aggregate (GROUP BY) function which returns a String value, if the group contains at least one non-NULL value. Otherwise, it returns NULL.

What is the difference between concat and Group_concat in MySQL?

The difference here is while CONCAT is used to combine values across columns, GROUP_CONCAT gives you the capability to combine values across rows. It's also important to note that both GROUP_CONCAT and CONCAT can be combined to return desired results.

What is separator in MySQL?

The SEPARATOR specifies a literal value inserted between values in the group. If you do not specify a separator, the GROUP_CONCAT function uses a comma (,) as the default separator. The GROUP_CONCAT function ignores NULL values.


1 Answers

Found a way to do this :

SELECT state,GROUP_CONCAT(cast(total as char))
FROM
(
    SELECT state,SUM(i.quantity) total
    FROM shops s
    LEFT JOIN items i ON i.shop=s.shopid
    WHERE state=5
    GROUP by item
) s
like image 158
Mahks Avatar answered Nov 19 '22 17:11

Mahks