如何计算直方图的连续行之间的差异?

时间:2015-11-03 17:58:12

标签: sql sql-server

我正在尝试从某些数据创建直方图。 SQL Server Developer 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

1 个答案:

答案 0 :(得分: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