【发布时间】:2020-03-19 23:01:51
【问题描述】:
我想根据下面给出的问题陈述来验证我写的SQL查询是否正确或可以改进。
Table t1 存储客户完成的付款,Table 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;
【问题讨论】:
-
(1) MySQL 和 PL/SQL 不一致。请标记您真正使用的数据库。 (2) 您的代码使用了诸如
order_id等不在您的示例数据中的列。 -
给定的 (sql?) 语句返回此错误:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''complete')请参阅dbfiddle