SQL GROUPBY&一列的总和

时间:2015-06-25 11:43:08

标签: mysql sql

我有一个包含以下结构的表

class Foo{


    Foo(I i, I1 i1){

        super();
        this(i);
        ...
    }

    Foo(I i){
        super();
        ...
    }
}

我希望获得以下输出 -

+------------+--------+------------------+-----+
|    E_DATE    | CLIENT |       TIME       | INS |
+------------+--------+------------------+-----+
| 2015-06-04 | comA   | 0.00478515625    |  a1 |
| 2015-06-04 | comA   | 0.0025390625     |  a1 |
| 2015-06-04 | comA   | 0.0              | a1  |
| 2015-06-04 | comA   | 0.0              | a1  |
| 2015-06-04 | comB   | 0.0115234375     | a2  |
| 2015-06-04 | comB   | 1.953125E-4      | a2  |
| 2015-06-04 | comB   | 0.0103515625     | a3  |
| 2015-06-04 | comB   | 0.0              | a3  |
| 2015-06-05 | comA   | 0.00478515625    | a4  |
| 2015-06-05 | comA   | 0.0025390625     | a4  |
| 2015-06-05 | comA   | 0.0              | a1  |
| 2015-06-05 | comA   | 0.0              | a2  |
| 2015-06-05 | comB   | 0.010351         | a1  |
| 2015-06-05 | comB   | 0.05625          | a1  |
+------------+--------+------------------+-----+

这是实现此目的的正确查询吗?

+------------+--------+-----+-----------------------------------------------------------+ 
|    E_DATE    | CLIENT | INS |                        TOTAL_TIME                         |
+------------+--------+-----+-----------------------------------------------------------+
| 2015-06-04 | comA   | a1  | SUM of TIME for a1 for comA for the date in 'E_DATE' column |
| 2015-06-04 | comB   | a2  | SUM of TIME for a2 for comA for the date in 'E_DATE' column |
| 2015-06-04 | comB   | a3  | SUM of TIME for a3 for comA for the date in 'E_DATE' column |
| 2015-06-05 | comA   | a1  | SUM of TIME for a1 for comA for the date in 'E_DATE' column |
| 2015-06-05 | comA   | a2  | SUM of TIME for a2 for comA for the date in 'E_DATE' column |
| 2015-06-05 | comA   | a4  | SUM of TIME for a2 for comA for the date in 'E_DATE' column |
| 2015-06-05 | comB   | a1  | SUM of TIME for a1 for comA for the date in 'E_DATE' column |
+------------+--------+-----+-----------------------------------------------------------+

3 个答案:

答案 0 :(得分:1)

我认为应该是:

select E_DATE, CLIENT, INS, SUM(TIME) AS TOTAL_TIME 
from Tablename
group by E_DATE, CLIENT, INS

因为在您的示例中,您要按3列E_DATE, CLIENT, INS分组并累积TIME列。

答案 1 :(得分:1)

你应该 SUM(TIME而不是

select E_DATE, CLIENT,INS,SUM(`TIME`) AS TOTAL_TIME 
FROM mytable
GROUP BY E_DATE,CLIENT

答案 2 :(得分:1)

如果我理解正确,那么这应该是答案,否则我/我们将需要您预期结果中SELECT E_DATE, CLIENT, INS, (SELECT SUM(time) FROM mytable b WHERE a.E_DATE = b.E_DATE AND a.INS = b.INS AND b.CLIENT = 'comA') TOTAL_TIME FROM mytable a GROUP BY E_DATE,CLIENT,INS 列的实际数字:

INS

注意:根据逻辑假设第二行的a4class MyObject

SQL Fiddle