I've got the following dataset ordered by a specific column:

ratio
-----
1
1
1
0.8333
1
1.6667
3.3333
1

And I want to count the rows where ratio equals 1, but only until I reach a row where ratio is not 1. For the above dataset my expected result would be 3 (the first three rows).

Of course I could do this in the code, but I just wondered whether there's an SQL solution to this.

  • Post the code that produces that result – Madhivanan Jul 21 '15 at 10:20
  • What is the column name for order by ? – Abhik Chakraborty Jul 21 '15 at 10:22
  • It does not really matter, but in my case it was "updated_at" – Webfarmer Jul 21 '15 at 12:53
up vote 2 down vote accepted

You say that the data is "ordered by a specific column". If so, you can simply do:

select count(*)
from table t
where specificcolumn < (select min(t2.specificcolumn)
                        from table t2
                        where t2.ratio <> 1)

Depending on the ordering, the < may need to be >.

Note: this assumes that the specific column has unique values. If the values are not unique, then you need multiple columns for a unique key.

  • Thanks, that works like a charm! I've used the following query now: select count(*) from table where updated_at > (select max(updated_at) from table where ratio <> 1) – Webfarmer Jul 21 '15 at 11:42

You can also try to use update

declare @cnt int, @flag int
select @cnt = 0, @flag = null
update #t set
    @cnt = @cnt + case when @flag is null then ratio else 0 end,  
    @flag = case when @flag is null and ratio != 1 then 1 else @flag end
select @cnt

I am using t-sql syntax, but you may find something similar in

If you have another primary key column in the table:

SELECT COUNT(`id`)
FROM `table`
WHERE `ratio` = 1
AND `id` < (SELECT `id` FROM `table` WHERE `ratio` != 1 ORDER BY `id` ASC LIMIT 0, 1)

Your Answer

 

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.