我的表格中有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
答案 0 :(得分: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
答案 1 :(得分:0)
我不会在一个sql-cell中连接它们,而是将它存储在不同的单元格中:
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
;
如果表格越来越长,请考虑动物表并引用它,而不是存储每个商店的动物名称或与其相关的任何内容