-2

I have a table like this:

CREATE TABLE tbltest (
  Col1           Integer(10) UNSIGNED,
  Col2           Integer(10) UNSIGNED
)

An there is the sample values:

Col1 Col2
---------
1     1   
2     1   
3     1   
4     1   
5     1   

6     2   
7     2   
8     2   
9     2   
10    2   

11    1   
12    1   
13    1   
14    1   
15    1   

I want to SELECT SUM(col1) GROUPBY sequence values of col2 not by all values. With above data results is like this:

col1 col2 
---------
15    1   
40    2   
75    1   

I don't have any idea how the query is looks like. Also forgive me for this bad title. I don't know what it should be called.

Thanks

4

3 回答 3

3

由于 MySQL 中缺少分析功能,版本有点复杂;我假设这是SUMval1需要的;

SELECT SUM(val1) val1, MAX(val2) val2
FROM (
  SELECT s1.val1, COUNT(s3.val1) grouping, s1.val2 val2
  FROM sequence s1
  LEFT JOIN sequence s2 ON s1.val1 >= s2.val1
  LEFT JOIN sequence s3 ON s3.val1 = s2.val1 - 1 AND s2.val2 <> s3.val2
  GROUP BY s1.val1
) a
GROUP BY grouping
ORDER BY grouping

一个用于测试的 SQLfiddle

如果您添加grouping到选择列表以使顺序明显,您会得到

val1    val2    grouping
15      1       0
40      2       1
65      1       2
于 2013-07-28T10:04:28.900 回答
1

您将需要使用 SUM() 函数和 GROUB BY。

所以要得到你正在寻找的答案

我能得到的最接近的是不添加其他列:

SELECT SUM(val1) as total1, val2 FROM table_name
GROUB BY table_name.val2

结果:

total1 val2
---------
93    1
30    2

您可能需要使第三列可用,以使三个组区分开来,例如

val1 val2 val3(new)
---------------
1    1   1
2    1   1
3    1   1
...  ..  ..
6    2   2
7    2   2
...  ..  ..
11   1   3
12   1   3
...  ..  ..
15   1   3

然后您的 SQL 查询变为:

SELECT SUM(val1) as total2, val2 FROM table_name
GROUB BY table_name.val2, table_name.val3

结果:

total1 val2
---------
15    1
30    2
78    1

参考在这里输入链接描述

于 2013-07-28T10:03:40.957 回答
0

尝试这个

    select sum(val1) as val1, val2 from table1
    group by val2
于 2013-07-28T10:01:47.367 回答