MySQL:使用group by选择并除以计数

时间:2017-04-27 13:01:34

标签: mysql sql

这是我表格的数据集

ID  |groupID|   Start   | End   | SegStart  | SegEnd    | something
-------------------------------------------------------------------
1   |   1   |   0.234   | 0.345 |   0.345   |   0.677   | 0
2   |   1   |   0.234   | 0.345 |   0.346   |   0.678   | 0
3   |   1   |   0.234   | 0.345 |   0.347   |   0.679   | 0
4   |   1   |   0.234   | 0.345 |   0.348   |   0.680   | 1
5   |   2   |   0.345   | 0.567 |   0.568   |   0.570   | 0
6   |   2   |   0.345   | 0.567 |   0.569   |   0.571   | 1
7   |   3   |   0.567   | 0.678 |   0.679   |   0.681   | 0
8   |   3   |   0.567   | 0.678 |   0.680   |   0.682   | 0
9   |   3   |   0.567   | 0.678 |   0.681   |   0.683   | 1

我想从开始/结束列以及SegStart / SegEnd列中计算某个值=“1”的值,然后将该值除以组中的项目数(组1有4个项目,组2有2,第3组有3等)

我已经尝试过这个查询,但它给出了错误“Subquery返回超过1行”

select (((End - Start) - (SegEnd - SegStart)) / 
  (select count(*) as NumSeg from table group by groupID)) as NewValue 
from table where something = "1"; 

我想要一个每个组的新值列表,有点像这样(值是虚构的):

groupID |   NewValue
--------------------
1       |   0.102
2       |   0.110   
3       |   0.036

1 个答案:

答案 0 :(得分:1)

你可以试试这个:

CREATE TABLE mytable(
   ID        INTEGER  NOT NULL PRIMARY KEY 
  ,groupID   INTEGER  NOT NULL
  ,Start     NUMERIC(11,3) NOT NULL
  ,End       NUMERIC(7,3) NOT NULL
  ,SegStart  NUMERIC(11,3) NOT NULL
  ,SegEnd    NUMERIC(11,3) NOT NULL
  ,something BIT  NOT NULL
);
INSERT INTO mytable(ID,groupID,Start,End,SegStart,SegEnd,something) VALUES (1,1,0.234,0.345,0.345,0.677,0);
INSERT INTO mytable(ID,groupID,Start,End,SegStart,SegEnd,something) VALUES (2,1,0.234,0.345,0.346,0.678,0);
INSERT INTO mytable(ID,groupID,Start,End,SegStart,SegEnd,something) VALUES (3,1,0.234,0.345,0.347,0.679,0);
INSERT INTO mytable(ID,groupID,Start,End,SegStart,SegEnd,something) VALUES (4,1,0.234,0.345,0.348,0.680,1);
INSERT INTO mytable(ID,groupID,Start,End,SegStart,SegEnd,something) VALUES (5,2,0.345,0.567,0.568,0.570,0);
INSERT INTO mytable(ID,groupID,Start,End,SegStart,SegEnd,something) VALUES (6,2,0.345,0.567,0.569,0.571,1);
INSERT INTO mytable(ID,groupID,Start,End,SegStart,SegEnd,something) VALUES (7,3,0.567,0.678,0.679,0.681,0);
INSERT INTO mytable(ID,groupID,Start,End,SegStart,SegEnd,something) VALUES (8,3,0.567,0.678,0.680,0.682,0);
INSERT INTO mytable(ID,groupID,Start,End,SegStart,SegEnd,something) VALUES (9,3,0.567,0.678,0.681,0.683,1);


select A.GROUPID, ((End - Start) - (SegEnd - SegStart)) / B.NumSeg AS V1
from mytable A
INNER JOIN  (select GROUPID, count(*) as NumSeg from mytable group by GROUPID) B ON A.GROUPID = B.GROUPID
where something = "1"; 

输出:

    GROUPID V1
1   1   -0,0552500
2   2   0,1100000
3   3   0,0363333