2015-11-03 84 views
1

我正試圖從一些數據創建一個直方圖。 SQL Server開發人員2014如何計算直方圖的連續行之間的差異?

數據結構:

+-------------Simulations------------+ 
+ ID | Cycle | Xa  | nextCycleShort + 
+ 0 | 0  | 5.63 | True   + 
+ 0 | 1  | 11.45 | False   + 
+ 0 | 2  | 12.3 | True   + 

+-Parameters-+ 
+ ID | CR + 
+ 0 | 1 + 
+ 1 | 2 + 

在數組符號,我想是這樣的表格:

(Xa[i + 1] - Xa[i])*(CASE nextCycleShort[i] WHEN 0 THEN 1.0 ELSE 2.0) AS DIFF 

從這個表,我要選擇COUNT(CAST(DIFF as int))。我想通過CAST(DIFF as INT),Parameters.CR進行分組。

因此,對於每個CR,我將能夠製作DIFF的直方圖。這看起來像什麼?這是我的嘗試:

SELECT 
    p.ControlRange as ControlRange, 
    CAST(DIFF as int) as XaMinusXb, 
    Count(DIFF) as total_diffs, 
    Select q.Xnew FROM 
    (SELECT Top 1 Xa AS Xnew 
     FROM Simulations t 
     WHERE t.ExperimentID = s.ExperimentID AND t.CycleCount > s.CycleCount 
     ORDER BY CycleCount DESC) q, 
    (q.Xnew - s.Xa)*(CASE WHEN s.nextCycleShort = 0 then 1.0 ELSE 2.0) AS DIFF 
FROM Simulations s join Parameters p 
GROUP BY CAST(DIFF as int), p.ControlRange 
ORDER by p.controlRange ASC, DIFF ASC 
     on s.ExperimentID = p.ExperimentID 
+0

什麼是sql server版本? –

+0

2014 Developer Edition – ijustlovemath

+1

您可能還想查看SQL Server 2012中引入的SQL Server窗口函數:http://sqlmag.com/sql-server-2012/how-use-microsoft-sql-server-2012s-window -functions-part-1 – pmbAustin

回答

0

只是想這樣做。每一行都回顧以前的Xa。你可以看到我們如何得到簡單的差異以及基於事例的乘數DIFF:

select 
    p.CR, s.Xa, 
    lag(s.Xa) over (partition by p.CR order by cycle asc) prev_Xa, 
    s.Xa - lag(s.Xa) over (partition by p.CR order by cycle asc) diff, 
    case when nextCycleShort = 'False' 
     then 1.0 
     else 2.0 
    end nextCyleShort_int, 
    (s.Xa - lag(s.Xa) over (partition by p.CR order by cycle asc)) * (case when nextCycleShort = 'False' then 1.0 else 2.0 end) myDIFF 
from 
    (
    select 0 ID, 0 Cycle, 5.63 Xa , 'True' nextCycleShort union 
    select 0 ID, 1 Cycle, 11.45 Xa , 'False' nextCycleShort union 
    select 0 ID, 2 Cycle, 12.3 Xa , 'True' nextCycleShort 
    ) s 
join 
    (
    select 0 ID, 1 CR union 
    select 1 ID, 2 CR 
    ) p 
on s.ID = p.ID