我有以下需要格式化的SQL表(下面是它的一个例子)。我想对客户订单ID进行分组,因此它只显示每个订单一次,如果“平衡”,我希望将“订单完成”列设置为1。 值等于或高于要交付的'在具有相同订单ID的每一行上。
编辑:每行客户ID可以有不同的商品编号(我没有在表格中包含artnr),所以检查总余额>交付是不够的,每行必须有足够的余额,最终将订单完成设置为1。
使用SQL有一种简单的方法吗?
Customer Order ID Customer Balance To Be Delivered Pick Date Delivery Date Order Complete
119290 Customer A 40 40 37546 37911 0
118886 Customer B 4 4 37546 37911 0
119575 Customer B 0 1 37546 37911 0
119575 Customer B 34 22 37546 37911 0
118776 Customer C 934 600 37911 38277 0
P119630 Customer D 0 1 37911 38277 0
P119630 Customer D 0 1 37911 38277 0
119347 Customer E 0 10 37911 38277 0
119476 Customer F 0 8 37911 38277 0
119476 Customer F 8 8 37911 38277 0
119476 Customer F 0 16 37911 38277 0
119476 Customer F 0 16 37911 38277 0
119476 Customer F 48 48 37911 38277 0
119476 Customer F 48 48 37911 38277 0
119476 Customer F 48 48 37911 38277 0
最终结果将是这样的。
Customer Order ID Customer Pick Date Delivery Date Order Complete
119290 Customer A 37546 37911 1
118886 Customer B 37546 37911 1
119575 Customer B 37546 37911 0
118776 Customer C 37911 38277 1
P119630 Customer D 37911 38277 0
119347 Customer E 37911 38277 0
119476 Customer F 37911 38277 0
答案 0 :(得分:1)
如果选择日期和交货日期在同一订单上的商品之间可能有所不同,则需要确定是否需要分组列表中的第一个或最后一个日期。我在这个例子中选择了其中一个。
SELECT id,
customer,
MIN(pick_date) AS first_pick,
MAX(delivery_date) AS last_delivery_date,
MIN(CASE WHEN balance >= to_be_delivered THEN 1 ELSE 0 END) AS complete
FROM my_table
GROUP BY id, customer
编辑代码一遍又一遍地重构......
答案 1 :(得分:0)
您可以在ANSI SQL
中尝试此操作SELECT order_id,customer, pick_date, delivery_date,CASE WHEN SUM(old_order_complete) = COUNT(order_id) THEN 1 ELSE 0 END AS order_complete
FROM (SELECT order_id,customer, pick_date, delivery_date, CASE WHEN balance >= to_be_delivered THEN 1 ELSE 0 END AS old_order_complete
FROM your_table)a
GROUP BY order_id,customer, pick_date, delivery_date
ORDER BY customer;