在SQL中计算两行与其他两个条件的差异

时间:2016-10-24 10:42:15

标签: sql sql-server

我想知道如何在SQL中为我的数据集执行以下操作,如下所示。对于每一行:

  1. 关于MachCode和WorkType(即按这两个顺序排列)
  2. 我想在新列中计算从一个日期(和时间)到另一个日期(和时间)的直径变化。如果没有差异,请填写零。
  3. 同样适用于厚度和坡度。 (在新专栏中)
  4. 数据:

    MachCode    WorkType    Date    Time    Diam    Thickness   Slope
    
    XHPUS0001   Lathing 07MAY07 0:00    873.30000   .   .
    XHPUS0001   Lathing 13DEC07 9:55    863.80000   .   .
    XHPUS0001   Lathing 05FEB10 8:40    863.80000   .   .
    XHPUS0001   Lathing 03APR12 14:32   890.60000   32.5000 11.0000
    XHPUS0001   Facing  02JAN13 19:24   876.00000   .   .
    XHPUS0001   Lathing 12JAN15 7:00    .   .   .
    XHPUS0002   Lathing 07MAY07 0:00    890.90000   .   .
    XHPUS0002   Lathing 07SEP09 7:26    890.90000   32.5000 .
    XHPUS0002   Facing  29NOV10 12:15   884.45000   32.5000 .
    XHPUS0002   Lathing 10SEP11 20:46   878.85000   .   .
    XHPUS0002   Lathing 04FEB12 21:49   874.10000   30.0000 loka.00
    XHPUS0003   Lathing 19SEP07 0:00    879.90000   .   .
    XHPUS0003   Lathing 23.marras.09    15:49   870.80000   .   .
    XHPUS0003   Lathing 4.marras.10 15:15   870.80000   .   .
    XHPUS0003   Lathing 06NOV10 13:24   864.10000   .   .
    XHPUS0003   Facing  27APR11 10:13   852.30000   .   .
    XHPUS0003   Lathing 17SEP11 19:31   847.00000   .   .
    XHPUS000323 Lathing 17FEB09 0:00    868.05000   .   .
    XHPUS000323 Lathing 22NOV09 12:50   868.05000   31.5100 loka.00
    XHPUS000323 Lathing 06SEP10 13:35   857.80000   31.5100 loka.00
    XHPUS000323 Lathing 02NOV10 15:00   890.80000   28.0000 .
    XHPUS000323 Lathing 26SEP11 11:11   879.70000   .   .
    XHPUS000323 Lathing 29DEC11 13:04   859.50000   30.5000 .
    XHPUS000323 Lathing 28JAN12 8:53    857.60000   .   .
    XHPUS000323 Lathing 28JAN12 11:58   857.60000   .   .
    XHPUS000323 Lathing 13OCT12 19:37   852.15000   .   .
    XHPUS000323 Lathing 31OCT12 14:03   890.50000   32.5000 11.0000
    XHPUS000323 Facing  16.marras.13    19:52   888.70000   .   .
    XHPUS000323 Lathing 12OCT13 13:49   886.70000   30.8000 loka.00
    XHPUS000323 Lathing 12OCT13 14:17   886.70000   30.8000 loka.00
    

    我尝试使用选择代码

    select * from T1 order by MachCode, WorkType, Date, Time;
    

1 个答案:

答案 0 :(得分:0)

外部适用于相同类型的TOP 1,其中日期较早,我们按日期降序排序

select T1.*,  
       COALESCE(T1.Diam - DQ.Diam , 0) DiamDelta, 
       COALESCE(T1.thickness - DQ.thickness,0) ThicknessDelta,
       COALESCE(T1.slope - DQ.slope,0) SlopeDelta from T1 

        OUTER APPLY (SELECT TOP 1 T1A.diam, T1A.thickness,T1A.slope FROM T1 T1A 
                    WHERE T1A.MachCode = T1.MachCode 
                            AND T1A.WorkType     = T1.WorkType     
                            AND (T1A.DATE < T1.Date OR T1A.DATE = T1.Date AND T1A.Time < T1.Time)
                    ORDER BY T1A.Date DESC , T1A.time DESC) DQ
    order by T1.MachCode, T1.WorkType, T1.[Date], T1.[Time];