MySql查询选择1个表的总和和最小记录

时间:2013-02-27 09:01:19

标签: mysql sql select

我有1个表,我想查询特定列。    Aa - >是截然不同的,

Bb - >总和B按Aa分组,

Cc - >特定Aa的最小值C,

Bb1,Dd - > B,D最小值时的D值,

Ee - >不同的

表1

id | A | B | C | D | E |
------------------------
1  | 2 | 1 | 2 | 1 | A |

2  | 2 | 2 | 7 | 0 | A |

3  | 4 | 1 | 7 | 3 | B |

4  | 4 | 0 | 5 | 4 | B |

结果

Aa | Bb | Cc | Bb1 | Dd | Ee |
-----------------------------
2  | 3  | 2  | 1   | 1  | A  |

4  | 1  | 5  | 0   | 4  | B  |

我的查询给出了错误的结果

  SELECT
    test.A as Aa,
    SUM(test.B) as Bb,
    min(test.C) as Cc,
    test.D as Dd,
    test.E as Ee
    FROM `test` 
    group by A,E

1 个答案:

答案 0 :(得分:0)

SELECT
      a.A as Aa,
      SUM(a.B) as Bb,
      min(a.C) as Cc,
      b.b B1,
      b.D DD,
      a.E EE
FROM  `Table1` a
      INNER JOIN
      (
        SELECT  a.*
        FROM    table1 a
                INNER JOIN
                (
                  SELECT  A, MIN(C) min_C
                  FROM    table1
                  GROUP   BY A
                ) b ON  a.a = b.a AND a.c = b.min_C
      ) b ON a.a = b.a 
group by a.A, b.b