2015-07-21 44 views
0

我有一个特定的列排序下面的数据集:SQL查询返回的行数,直到满足一定的条件

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

而且我想算哪里比等于1的行,但只能,直到我达到一个行的比例不是 1. 对于上述数据集我的预期结果将是(前三行)。

当然,我可以在代码中这样做,但我只是想知道是否有SQL解决方案。

+0

后,其产生的结果 – Madhivanan

+0

什么是列名的代码按顺序? –

+0

这并不重要,但在我的情况下,它是“updated_at” – Webfarmer

回答

2

你说的数据是“由一个特定的列排序”。如果是这样,你可以简单地做:

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

根据排序,该<可能需要>

注意:这里假设特定列具有唯一值。如果这些值不唯一,那么您需要多个列来存储唯一密钥。

+0

谢谢,这就像一个魅力!我现在使用了以下查询: select table(*)from where where updated_at>(从表中选择max(updated_at),比例<> 1) – Webfarmer

1

如果你在表中的另一主键列:

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

您也可以尝试使用更新

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 

我使用T-SQL的语法,但你会发现类似的东西在