I have a mysql
table like this:
Person x minutes population
p1 F 3 p1p2p3p4
p2 B 1 p1p2p3p4
p1 B 7 p1p2p3
p3 F 2 p2p3p1
p1 F 3 p1p2
p1 B 4 p2p3p1
p2 C 3 p1p2p3
p2 B 1 p2p1p3
p2 F 7 p2p3p4
p3 B 2 p2p3p4
p1 F 3 p2p1p3p4
What I need to select, for each Person
is:
1- Count the number of times x is equal to F
;
2- Count the number of times x is equal to B
;
3- Sum the value of minutes
when the person
appears in the variable population
;
Then, the resulting select
would be like this:
Person nF nB tminutes
p1 3 2 24
p2 1 2 36
p3 1 1 33
I am not sure if this is even possible. I have tried something like:
SELECT
Person,
sum(x='F') as nF,
sum(x='B') as nB,
sum(minutes) WHERE population IS LIKE '%Person%' as tminutes
FROM myTable
GROUP BY Person
Any ideas would be very welcome! Thanks.
You can use the following solution, using a sub-select:
SELECT
Person,
SUM(IF(x = 'F', 1, 0)) AS nF,
SUM(IF(x = 'B', 1, 0)) AS nB,
(SELECT SUM(minutes) FROM test_table WHERE INSTR(population, t1.Person) > 0) AS tminutes
FROM test_table t1
GROUP BY Person
The result of this query:
Person | nF | nB | tminutes
---------------------------
p1 | 3 | 2 | 27
p2 | 1 | 2 | 36
p3 | 1 | 1 | 33
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.