简体   繁体   English

复杂(或不可能)从mysql表中选择

[英]Complex (or impossible) Select from mysql table

I have a mysql table like this: 我有一个像这样的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

What I need to select, for each Person is: 我需要为每个Person选择的是:

1- Count the number of times x is equal to F ; 1-计算x等于F

2- Count the number of times x is equal to B ; 2-计算x等于B

3- Sum the value of minutes when the person appears in the variable population ; 3-将person出现在可变populationminutes总和;

Then, the resulting select would be like this: 然后,结果select将如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM