我有5个不同的列,每行有100多行,每行都有各种各样的数字。
我已经能够计算第1列中等于3
的所有值我希望能够计算所有5个不同列中的所有数字3并添加它们
$countquery = "SELECT COUNT(*) FROM PowerBall WHERE W1=3";
$countresult = mysql_query($countquery) or die(mysql_error());
while($countrow = mysql_fetch_array($countresult)) {
echo "<br />";
echo "There are ". $countrow['COUNT(*)']."-3s";
}
答案 0 :(得分:4)
您可以使用带有CASE
表达式的聚合函数来获取所有列中3个值的总数。
Select
sum(case when col1 = 3 then 1 else 0 end) TotalCol1,
sum(case when col2 = 3 then 1 else 0 end) TotalCol2,
sum(case when col3 = 3 then 1 else 0 end) TotalCol3,
sum(case when col4 = 3 then 1 else 0 end) TotalCol4,
sum(case when col5 = 3 then 1 else 0 end) TotalCol5
from PowerBall
如果您想在一列中使用此功能,则可以使用:
select TotalCol1 + TotalCol2 + TotalCol3 + TotalCol4 + TotalCol5
from
(
Select
sum(case when col1 = 3 then 1 else 0 end) TotalCol1,
sum(case when col2 = 3 then 1 else 0 end) TotalCol2,
sum(case when col3 = 3 then 1 else 0 end) TotalCol3,
sum(case when col4 = 3 then 1 else 0 end) TotalCol4,
sum(case when col5 = 3 then 1 else 0 end) TotalCol5
from PowerBall
) src
甚至:
select sum(Total)
from
(
Select count(col1) Total
from PowerBall
where col1 = 3
union all
Select count(col2)
from PowerBall
where col2 = 3
union all
Select count(col3)
from PowerBall
where col3 = 3
union all
Select count(col4)
from PowerBall
where col4 = 3
union all
Select count(col5)
from PowerBall
where col5 = 3
) src
答案 1 :(得分:1)
SELECT SUM(CASE WHEN COL1 = 3 THEN 1 ELSE 0 END) AS 'Col1',
SUM(CASE WHEN COL1 = 3 THEN 1 ELSE 0 END) AS 'Col2',
....
FROM PowerBall WHERE W1 is not null