如何否定无效的订单数据?

时间:2018-10-04 21:31:21

标签: sql sql-server

我有一个有趣的订单历史记录表,如下所示:如果用户取消订单,则系统不会更新原始订单,但是会在同一日期输入负数量和负成本的新订单,例如:

user_id  date        qty    cost
1        2018-10-01   2    100.00  -- a wrong order
1        2018-10-01  -2   -100.00  -- negate the above order
1        2018-10-01   2    100.00  -- this is a valid order
1        2018-10-01   3    150.00  -- this is a valid order
1        2018-10-01   1     50.00  -- this is a valid order 

如何创建仅包含有效订单的清理表,

user_id  date        qty    cost
1        2018-10-01   2    100.00 
1        2018-10-01   3    150.00
1        2018-10-01   1     50.00  

我尝试使用按日期分组,但这不好,因为它可能会在一天内压缩多个有效订单。

如果有人可以帮助我直接在sql server中执行此操作,将非常方便!否则,我只是编写一个python脚本来加载数据并在外部执行此操作...

1 个答案:

答案 0 :(得分:3)

这不是一个好的设计。您确实需要一个order_id。天真的解决方案是not exists

select o.*
from orders o
where not exists (select 1 from orders o2 where o2.user_id = o.user_id and o2.date = o.date and o2.qty = - o.qty and o2.cost = - o.cost);

A,某人一天之内可以订购两次,然后仅取消其中的一项。因此,您需要柜台。因此,请使用row_number()

with o as (
      select o.*,
             row_number() over (partition by user_id, date, qty, cost order by user_id) as seqnum
      from orders o
     )
select o.*
from o
    where not exists (select 1
                      from orders o2
                      where o2.user_id = o.user_id and o2.date = o.date o2.seqnum = o.seqnum and
                            o2.qty = - o.qty and o2.cost = - o.cost
                     );