SQL - 作为子查询的结果删除所有记录

时间:2018-05-09 01:38:25

标签: sql sql-server-2012

我真的很难在这里实施解决方案。

    SELECT 
      mach_id, 
      value1, 
      CASE 
        WHEN value1 = 0 THEN lead(created_on) OVER (ORDER BY mach_id)
      END, 
      created_on
    FROM MyTable
    WHERE 
      field_name='someValue' and 
      CAST(created_on AS DATE) = CAST(GETDATE() AS DATE)

我需要在value1为0时获取created_on日期,然后获取创建日期的潜在记录。然后取这些日期并删除另一个表中的所有记录,其中created_on在这两个日期之间由mach_id。

我真的对这里的解决方案感到茫然。有什么建议吗?

1 个答案:

答案 0 :(得分:0)

我终于提出了解决方案,我发布它希望它能帮助别人。感谢大家的意见和建议。

    Delete fe from MySecondTable fe join
(Select * from
    (
        Select mach_id, station_id, 
        lag(value1) over (partition by mach_id order by created_on) as shiftEndValue,
        CASE WHEN value1=0 THEN lag(created_on) over (partition by mach_id order by created_on)
            end as shiftEndTime,
            value1, created_on
            FROM MyFirstTable
            where field_name='cur_trgt_cnt' and CAST(created_on AS DATE) = CAST(GETDATE() AS DATE)
    )a
    where shiftEndTime is not null
)b
on fe.mach_id= b.mach_id and fe.station_id=b.station_id 
where fe.created_on between b.shiftEndTime and b.created_on