SQL Server 如何更新多条件数据

suzh9iv8  于 2022-11-28  发布在  其他
关注(0)|答案(1)|浏览(165)

我有一个5列的表,如下表所示:

我希望根据以下条件填写批准栏:

APPROVAL = "Y" IN CASE
  (1) CUSTOMER_NEW <> CUSTOMER (as in the case CUSTOMER = 12467)  
  (2) CUSTOMER_NEW = CUSTOMER AND SALE_SHORT_ID COLUMN HAS DIFFERENT VALUE (as in the case CUSTOMER = 13579)  
  (3) CUSTOMER_NEW = CUSTOMER AND SALE_SHORT_ID HAS THE SAME VALUE THEN MAX(LEN(SALE_ID) (as in the case CUSTOMER = 65465)
ELSE "N"

我的结果预期会像这张表:

谢谢你的支持。

xtfmy6hx

xtfmy6hx1#

我不确定你的条件,但这一个可以做到这一点:

UPDATE a
SET approval =
    CASE WHEN
        a.customer <> a.customer_new OR
        a.customer = a.customer_new AND b.sale_short_eq = 0 OR
        a.customer = a.customer_new AND a.sale_id = b.max_len_sale_id
    THEN 'Y'
    ELSE 'N'
    END
FROM
    thetable a
    INNER JOIN (
        SELECT
            customer,
            CASE WHEN MIN(sale_short_id) = MAX(sale_short_id) THEN 1 ELSE 0 END AS sale_short_eq,
            ( SELECT TOP 1 sale_id 
              FROM thetable
              WHERE customer = c.customer
              ORDER BY LEN(sale_id) DESC
            ) AS max_len_sale_id
        FROM thetable c
        GROUP BY customer
    ) b
        ON a.customer = b.customer

请注意,列b.sale_short_eqb.max_len_sale_id是由联接到主查询的子查询返回的。
特别是SALE_SHORT_ID HAS THE SAME VALUE THEN MAX(LEN(SALE_ID)不清楚。您的意思是销售_ID必须与最大长度SALE_ID相同吗?因为SALE_SHORT_ID不能与任何SALE_ID相同。如果两个不同的SALE_ID具有相同的最大长度,会发生什么情况?
请参阅:https://dbfiddle.uk/7Ct87-Mk

相关问题