SQL通过联接2个表来验证列

时间:2019-11-24 14:08:58

标签: mysql sql plsql

我想根据下面给出的问题陈述来验证编写的SQL查询是否正确或可以改进。

表t1存储客户完成的付款,表t2包含客户购买的商品数量和订单状态。我想编写一个查询来验证每个订单的付款方式是否为qty * price_per_item。如果此条件为假,则在新列中打印差异。

===== Table t1 =====
customer_id    payment($)
    1             6
    2             20
    3             10

===== Table td =====
customer_id    qty    price_per_item($)  order_status
    1           3       2                 complete
    1           2       4                 cancelled
    2           2       3                 complete
    2           3       5                 complete
    3           5       2                 complete
    3           4       7                 cancelled

这是我编写的SQL查询内容,但不确定是否正确。

select A.customer_id,
       B.Rev,
       A.Multiply,
       (B.Rev - A.Multiply) as diff,
       case
         when (B.Rev - A.Multiply) > 0 then
          1
         else
          0
       end as Boolean
  from (select td.order_id,
               td.customer_id,
               sum(td.qty * td.price_per_item) over(partition by td.customer_id) As Multiply
          from td
         where td.order_status in 'complete') A
 inner join (select t1.customer_id, sum(t1.payment) Rev
               from t1
              group by t1.customer_id) B
    on A.customer_id = B.customer_id;

2 个答案:

答案 0 :(得分:0)

您要确保对于每个客户/订单元组,订单价格均已全额支付。您的样本数据缺少order_id,但我认为它在那里,因为您似乎是故意的。

从本质上讲,这是一个完整的外部联接。在MySQL中,我们可以使用union all来模拟。订单表每个订单有几条记录,因此我们需要在合并之前将其汇总(同时忽略已取消的订单)。然后,外部查询对具有相同客户和order_id的记录进行分组,并在having子句中将订单价格与已支付价格进行比较。

select 
    customer_id,
    order_id,
    max(price) total_price,
    max(paid) total_paid
from (
    -- get the amount ordered per customer_id/order_id
    select customer_id, order_id, sum(qty * price_per_item) price, null paid
    from td
    where order_status != 'cancelled'
    group by customer_id, order
    union all 
    -- get the amount paid per customer/order_id
    select customer_id, order_id, null, payment
    from t1
) t
group by customer_id, order_id
having not max(price) = max(paid)

答案 1 :(得分:0)

尝试一下:

     select order_status, price_per_item, qty, payment, price_per_item*qty as Multiply, payment- price_per_item*qty
     , case when payment- price_per_item*qty = 0 then 0 else 1 end as Boolean
      from td a inner join t1 on t1.customer_id = a.customer_id

让我们知道

通过这种方式,您的表中没有order_id