您可以使用带有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