如果在列A sql上已存在列B和列C的值,如何设置空值?

时间:2017-02-08 19:26:57

标签: sql sql-server-2008 conditional-statements repeat

Select BillName as A, ConsigneeName as B, ShipperName as C 
                              from Sum_Orders 
                              where (OrderStatus in ('Complete','Invoiced')
    ) 
    and 
    OrderPeriodYear IN (
    (
    YEAR(GETDATE())-1
    )
    )
    Group by billname,ConsigneeName,ShipperName

我在A,B,C中有重复(预计会有) 我正试图制造一个条件 将值保留在A中并设置为使在B或C

中重复的值为空

如果A = B或C,则将A和SET B或C保持为NULLS

enter image description here

谢谢你们,伙计们:D

3 个答案:

答案 0 :(得分:0)

这是你想要的吗?

update t
    set B = (case when B <> A then B end),
        C = (case when C <> A then C end)
    where B <> A or C <> A;

答案 1 :(得分:0)

如果你必须内联这样做,也许一个案例会有所帮助。

Select Billname AS A, 
CASE WHEN ConsigneeName = Billname THEN NULL ELSE ConsigneeName END, 
CASE WHEN ShipperName = Billname THEN NULL ELSE ShipperName 
from Sum_Orders etc ...

如果表很大,这在查询上可能很昂贵,并且将此逻辑推入查询本身可能会更好。

答案 2 :(得分:0)

如果a,b和c具有相同的值,则b和c应设置为null,因此:

 Update tablename
 Set B = if(A=B, null, B) , C=if(A=C, null, C)
 -- where A=B or A=C

如果优化很有意义,你可以使用'where'!

如果您要“选择”值:

 Select  A, if(A=B, null, B) as B , if(A=C, null, C) as C from tablename