[英]MySQL: select and divide by count using group by
Here's a data set of my table 这是我表的数据集
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
I want to calculate a value from the Start / End columns as well as the SegStart / SegEnd columns where something = "1" and then divide this value by the number of items in a group (group 1 has 4 items, group 2 has 2, group 3 has 3, etc) 我想从Start / End列以及SegStart / SegEnd列中计算出一个值,该值= 1,然后将该值除以组中的项目数(组1有4个项目,组2有2个项目,第3组有3个,依此类推)
I've tried this query, but it gives me the error "Subquery returns more than 1 row" 我已经尝试过此查询,但它给我错误“子查询返回多于1行”
select (((End - Start) - (SegEnd - SegStart)) /
(select count(*) as NumSeg from table group by groupID)) as NewValue
from table where something = "1";
I would like a list of the new value for each group, kind of like this (values are imaginary): 我想要每个组的新值的列表,像这样(值是虚数的):
groupID | NewValue
--------------------
1 | 0.102
2 | 0.110
3 | 0.036
You could try this: 您可以尝试以下方法:
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";
Output: 输出:
GROUPID V1
1 1 -0,0552500
2 2 0,1100000
3 3 0,0363333
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.