I have a query with sum aggregation function :
SELECT sum(case when result=1 then 1 when result=2 then 0)as final_result From results
I want to change this part when result=2 then 0
to something like that when result=2 then final_result equals zero
Is it possible to do this ? or there is another way for that?
Try this :
SELECT CASE WHEN cnt=sum THEN sum ELSE 0 END as Final_result
FROM
(
SELECT count(*) as cnt,
SUM(case when result=1 then 1 else 0 end) as sum
from results
) Temp
Working Fiddle here.
Explanation:
Inner query select the total number of records and the sum of the records. Then if those count and sum are equal that means all values are 1.
NB: Removed the checking when result=2 then 0
because, the query will select 0 for any values other than 1. So there is no need to check for result=2
.
EDIT:
To find the count of 10 consecutive 1's, you can do:
SELECT SUM(CASE WHEN RN=10 THEN 1 ELSE 0 END) AS final_result
FROM
(
SELECT CASE WHEN result=1 THEN @row_number:=@row_number+1 ELSE @row_number:=0 END AS RN,
result
FROM results, (SELECT @row_number:=0) AS t
) Temp
Sample Fiddle here.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments