2

我的表中有列infoanimal

RABBIT  || Male   || 15
HAMSTER || Female || 10
FROG    || Male   ||  5
RABBIT  || Male   || 40
HAMSTER || Male   ||  4
FROG    || Male   || 13

我在以下时刻有这个:

$sql = "SELECT * FROM experimental";
$query5 = mysql_query($sql);
while ($dados = @mysql_fetch_array($query)){
    $infoanimal = $dados["infoanimal"];
    $pesquisa = explode(">>", $infoanimal);
    $num_pesq = count($pesquisa);
    for($i=1;$i<$num_pesq;$i++){
        $dadosx3 = explode("||", $pesquisa[$i]);
        $animal[0] = $dadosx3[0];
        $gender[0] = $dadosx3[1];
        $amount[0] = $dadosx3[5];
    }
}

我想做以下事情:

Animal  || Male || Female || Sum
HAMSTER || 4    || 10     || 14
FROG    || 18   || 0      || 18
RABBIT  || 40   || 0      || 40
4

2 回答 2

0
SELECT  animal,
        SUM(CASE gender WHEN 'male' THEN amount ELSE 0 END) AS male,
        SUM(CASE gender WHEN 'female' THEN amount ELSE 0 END) AS female,
        SUM(amount) AS `sum`
FROM    infoanimal
GROUP BY
        animal
于 2013-05-07T20:06:05.223 回答
0

我不会将它们连接在一个 sql 单元中,而是将其存储在不同的单元中:

create table animal_info (
    some_row_id int, 
    animal_name varchar, 
    animal_gender enum('Male','Female','Herma'),
    number_animals int);

接着

SELECT 
    animal_name as animal,
    sum(if(animal_gender = 'Male', number_animals, 0)) as male,
    sum(if(animal_gender = 'Female', number_animals, 0)) as female,
    sum(number_animals) as sum
FROM
    animal_info
WHERE
    some_row_id = <row of old entry>
GROUP BY animal_name
;

如果表格变得更长,请考虑使用动物表格并引用它,而不是为每家商店或与之相关的任何东西存储动物名称

于 2013-05-07T20:12:33.560 回答