首页 > 解决方案 > CASE 表达式在百分比计算期间返回错误值

问题描述

我目前正在从事超市数据库设计,我必须在其中检索折扣后的产品价格。

有 2 种折扣类型:直接折扣、基于数量的折扣。该产品将有百分比折扣(例如:10% 折扣)或金额/现金折扣(例如:5 美元折扣)

目前,我的代码仅适用于基于数量的折扣,但不适用于将返回错误值的直接折扣(百分比折扣)。

select id, product_name, unitPrice,Product.discount_cd,
discount_percentange as 'Discount Percentage' , 
discount_amount as 'Discount Amount',
Promotion_Type.quantity,
case when Product.discount_cd NOT LIKE '%DD' AND discount_percentange IS NOT NULL 
    THEN (unitPrice*ISNULL(discount_percentange,1))*ISNULL(quantity,1)
 when (Promotion_Type.discount_cd NOT LIKE '%QB' AND Promotion_Type.discount_percentange IS NOT NULL)
    THEN (unitPrice-(unitPrice*discount_percentange))
ELSE (unitPrice*ISNULL(quantity,1))-(unitPrice*ISNULL(discount_percentange,0))-(ISNULL(discount_amount,0))
END AS reduce
from Product
LEFT JOIN Promotion_Type ON Product.discount_cd=Promotion_Type.discount_cd

根据附图,产品 P001 和 P005 的降价是错误的。我能知道错误在哪里吗?数据库表输出 数据库产品表截图

标签: sqlsql-server

解决方案


我看到您的CASE陈述存在多个问题。

首先,我认为您在滥用%通配符。它代表它所在位置的任意数量的任意字符。例如,'%DD'只要最后两个字符是“DD”,就表示任何内容。添加NOT只是翻转它。因此,Product.discount_cd NOT LIKE '%DD'只要Product.discount_cd不以 结尾'DD'(这是所有代码),就会评估为真。当您添加 时AND discount_percentage IS NOT NULL,结果是,任何具有 a 的记录都discount_percentage将与第一THEN条语句一起返回。这包括 P001 和 P005。

其次,我认为您在滥用该ISNULL()功能。没有必要discount_percentage按照您IS NOT NULL的标准使用它。另外,如果quantity是指产品数量,我认为您不应该在quantity为空时返回 1。

假设“DD”代表“直接折扣”,我不明白为什么您的记录带有“DD”代码而没有discount_percentage。话虽如此,我认为以下修订后的CASE声明将满足您的需求。

CASE
    WHEN
        Product.discount_cd LIKE 'DD%' --Any code beginning with 'DD'
        AND discount_percentage IS NOT NULL --Must have discount percentage
        THEN (unitPrice * ISNULL(quantity,0)) - (unitPrice * ISNULL(quantity,0) * discount_percentage)
    WHEN
        Promotion_Type.discount_cd LIKE 'QB%' --Any code beginning with 'QB'
        AND discount_amount IS NOT NULL --Must have discount amount
        THEN unitPrice * ISNULL(quantity,0) - discount_amount
    ELSE 0 --No valid discount
END AS reduce

推荐阅读