SELECT / GROUP BY - sequence of a value

安稳与你 提交于 2020-01-03 06:40:21

问题


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


回答1:


A bit of a complex version due to the lack of analytic functions in MySQL; I'm assuming it's the SUM of val1 you need;

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

An SQLfiddle to test with.

If you add grouping to the selection list to make the order obvious, you get

val1    val2    grouping
15      1       0
40      2       1
65      1       2



回答2:


You will need to use the SUM() function and GROUB BY.

So to get the answer you looking for

Closest I can get is without adding other columns:

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

Result:

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

You might need to made a third column available that makes the three groups distinc such as

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

Then your SQL query becomes:

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

Result:

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

Referring to enter link description here




回答3:


try this

    select sum(val1) as val1, val2 from table1
    group by val2


来源:https://stackoverflow.com/questions/17906940/select-group-by-sequence-of-a-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!