2015-07-21 45 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的語法,但你會發現類似的東西在