2015-08-22 21 views
0

我有一行x,整數範圍爲0 < x < = maxX。 要與我使用下面的語句SQLite中使用sqlite中的動態分區數創建直方圖

select case 
    when x > 0 and x <= 1*((maxX+4)/5) then 1 
    when x > 1*((maxX+4)/5) and x <= 2*((maxX+4)/5) then 2 
    when x > 2*((maxX+4)/5) and x <= 3*((maxX+4)/5) then 3 
    when x > 3*((maxX+4)/5) and x <= 4*((maxX+4)/5) then 4 
    else 5 end as category, count(*) as count 
from A,B group by category 

大小相等的5個分區創建直方圖有沒有辦法做一個「動態」查詢這我可以創建n的直方圖的方式分區沒有在case-statement中寫入n個條件?

+0

SQLite並不真的支持變量,所以你的問題有點不清楚。 –

回答

1

您可以使用算術來分割這些值。這是一種方法。它本質上利用了maxX/5值上限,並使用該定義分區:

select (case when cast(maxX/params.n as int) = maxX/params.n 
      then (x - 1)/(maxX/param.n) 
      else (x - 1)/cast(1 + maxX/params.n as int) 
     end) as category, count(*) 
from (select 5 as n) params cross join 
    A 
group by category; 

-1是因爲你的號碼在一個而不是從零開始。

+0

這看起來不錯。但是,當x接近maxX時,我注意到了錯誤。例如,令maxX = 499,n = 2,x = 499。那麼then-clause被執行並返回2,儘管應該只有0和1的類別。我認爲問題是when子句的條件總是被滿足,因爲因爲兩個參數都是整數,所以值被截斷演員。在我用maxX * 1.0/params.n = maxX/params.n替換條件後,它就像499/2的例子那樣工作。我沒有檢查一般結果是否正確。 –