SQL:根据序列计算字段

时间:2016-09-20 09:32:09

标签: sql vertica

我正在尝试计算线条的角度,以便在可视化中显示它们的方向。但是,我仍然坚持如何使用SQL select语句自动将其计算为数据库视图。

计算基于以下几个标准:

  1. 角度公式是INT(DEGREES(ATAN2(x2-x1,y2-y1))),其中x2 =相同行的x,并且x1 =根据序列字段的前一行的x。序列中的第一个将为NULL,因为它之前没有x,y。
  2. 计算在每个唯一的“行”值
  3. 内完成
  4. 当Direction = 1时,序列从最小值到最大值开始。但是,当Direction = 2时,序列从最大到最小。
  5. enter image description here

    以下是示例数据:

    Line,Direction,Sequence,Y,X
    Line 1,1,1,1.37707996,103.9108531
    Line 1,1,1.2,1.37765002,103.9118526
    Line 1,1,4.5,1.37849998,103.912852
    Line 1,1,6.2,1.37914002,103.9138515
    Line 1,1,8,1.37959003,103.9148509
    Line 1,1,11.1,1.37978005,103.9148509
    Line 1,1,13.1,1.38031006,103.9158504
    Line 2,2,1.1,1.29593003,103.8761495
    Line 2,2,2.4,1.29744005,103.8771489
    Line 2,2,5.5,1.29849005,103.8771489
    Line 2,2,8.1,1.29954004,103.8781484
    Line 2,2,10,1.30094004,103.8781484
    Line 2,2,11.1,1.30155003,103.8781484
    Line 2,2,13.1,1.30234003,103.8781484
    Line 2,2,15.1,1.30338001,103.8781484
    Line 2,2,16.6,1.30410004,103.8781484
    

    任何指针?谢谢。

1 个答案:

答案 0 :(得分:1)

也许是这样的......

SQL> create table angle ( 
         line varchar(10), direction integer, sequence float, 
         y float, x float) ;
SQL> select degrees(atan2(
          x - lag(x) over(order by sequence), 
          y - lag(y) over(order by sequence)
     ))::integer from angle ;

修改

当方向不是“1”时反转顺序顺序:

SQL> select case when direction = 1 then 
                degrees(atan2(x-lag(x) over(order by sequence), 
                y-lag(y) over(order by sequence)))::integer 
            else 
                degrees(atan2(x-lag(x) over(order by sequence desc), 
                y-lag(y) over(order by sequence desc)))::integer 
            end 
     from angle ;