1

我有 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";
}
4

2 回答 2

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
于 2013-02-22T22:13:22.513 回答
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
于 2013-02-22T22:15:10.807 回答