我有一个mysql
表,如下所示:
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
我需要为每个Person
选择:
1-计算x等于F
;
2-计算x等于B
;
3-在变量minutes
中出现person
时,population
的值总和;
然后,生成的select
将是这样的:
Person nF nB tminutes
p1 3 2 24
p2 1 2 36
p3 1 1 33
我不确定这是否可行。我尝试过类似的东西:
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
任何想法都会非常受欢迎!感谢。
答案 0 :(得分:2)
您可以使用以下解决方案,使用子选择:
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
此查询的结果:
Person | nF | nB | tminutes
---------------------------
p1 | 3 | 2 | 27
p2 | 1 | 2 | 36
p3 | 1 | 1 | 33