MySql - Grouping by a column of specific value only (without UNION)

时间:2017-06-15 10:24:59

标签: mysql

Given the following data;

column a | column b | column c
________   ________   _______
   A     | apple    |   1
   P     | pear     |   3
   O     | orange   |   4
   A     | apple    |   1
   P     | peach    |   2
   P     | pear     |   3
   P     | peach    |   1
   A     | apple    |   4

I would like to select and only group (and sum) by apple. The rest of the columns would not be grouped and so the following would be the output;

column a | column b | column c
________   ________   _______
   A     | apple    |   6
   P     | pear     |   3
   O     | orange   |   4
   P     | peach    |   2
   P     | pear     |   3
   P     | peach    |   1

Is the above possible without using a UNION?

1 个答案:

答案 0 :(得分:2)

不使用UNION

SELECT tbl.id,tbl.a,tbl.b,tbl.c FROM (
SELECT id,a,
    CASE WHEN b='apple' THEN @ap:= (@ap+c) ELSE c END as c,
    CASE WHEN b = (SELECT b FROM fruit WHERE id > frA.id AND b='apple' LIMIT 1) THEN b ELSE CONCAT(' ',b) END as b
    FROM fruit AS frA, (SELECT @ap:=0 ) AS apc
    ) as tbl
WHERE tbl.b REGEXP '^[ ].*$'

现场演示:SQL Fiddle