如何防止Order_ID重复?

时间:2015-01-19 20:02:42

标签: sql-server-2008

当我运行此查询时,我得到重复的行。具体而言,对于与该Customer_ID相关的每个可能的ship_state重复order_ID。如果我从查询中删除cust_address表,我会得到正确的行数。如何才能获得与该特定订单相关的Ship_states。谢谢。

SELECT     
    co.ID AS order_ID, 
    col.PART_ID, 
    col.ORDER_QTY, 
    co.STATUS, 
    co.SHIPTO_ID, 
    co.CUSTOMER_PO_REF, 
    co.CUSTOMER_ID, 
    c.STATE AS Bill_State, 
    ca.STATE AS Ship_State
FROM         
    dbo.CUSTOMER_ORDER AS co 
INNER JOIN
    dbo.CUST_ORDER_LINE AS col ON co.ID = col.CUST_ORDER_ID 
INNER JOIN
    dbo.CUSTOMER AS c ON co.CUSTOMER_ID = c.ID 
INNER JOIN
    dbo.CUST_ADDRESS AS ca ON c.ID = ca.CUSTOMER_ID
WHERE     
    (co.ORDER_DATE > '2014-01-01') AND (co.ID NOT LIKE 'rma%')
ORDER BY order_ID

1 个答案:

答案 0 :(得分:0)

这为我提供了每个送货地址的唯一订单行和订单号。接下来的挑战是找出一种方法来填充具有相同送货地址和帐单地址的行。对于这些订单,货运字段为空,而使用来自客户表的信息。

SELECT    ca.STATE AS ship_state, 
          co.ID, 
          co.CUSTOMER_ID, 
          ca.ADDR_NO, 
          co.SHIP_TO_ADDR_NO, 
          c.STATE AS Bill_state, 
          c.NAME AS Bill_name, 
          ca.NAME AS Ship_name
FROM    
        dbo.CUST_ORDER_LINE AS col 
FULL OUTER JOIN
        dbo.CUSTOMER_ORDER AS co ON col.CUST_ORDER_ID = co.ID 
FULL OUTER JOIN
        dbo.CUST_ADDRESS AS ca 
FULL OUTER JOIN
        dbo.CUSTOMER AS c ON ca.CUSTOMER_ID = c.ID 
ON      
        co.CUSTOMER_ID = c.ID 
AND     
        co.CUSTOMER_ID = ca.CUSTOMER_ID 
AND     
        co.SHIP_TO_ADDR_NO = ca.ADDR_NO
WHERE     
       (co.ORDER_DATE > '2014-1-1') AND (co.ID NOT LIKE 'rma%')
ORDER BY co.ID