case表达式在百分比计算期间返回错误的值

5gfr0r5j  于 2021-08-09  发布在  Java
关注(0)|答案(2)|浏览(261)

我目前正在超市数据库设计工作,我必须检索折扣后的产品价格。
有两种类型的折扣:直接折扣,数量折扣。产品将有百分比折扣(如:10%折扣)或金额/现金折扣(如:5美元折扣)
目前,我的代码只适用于基于数量的折扣,而不适用于直接折扣(百分比折扣),因为它将返回错误的值。

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

根据所附图片,产品p001和p005的降价是错误的。我能知道哪里出错了吗?数据库表output database product表的屏幕截图

xqkwcwgp

xqkwcwgp1#

我发现你的电脑有很多问题 CASE 声明。
首先,我认为你误用了 % 通配符。它表示它所在位置的任意数量的任意字符。例如, '%DD' 只要最后两个字符是'dd'就表示任何内容。添加 NOT 把它翻过来。因此, Product.discount_cd NOT LIKE '%DD' 只要 Product.discount_cd 不会以 'DD' ,这是所有代码。当你加入 AND discount_percentage IS NOT NULL ,结果是,任何具有 discount_percentage 会和第一个一起回来 THEN 声明。这包括p001和p005。
第二,我认为你误用了 ISNULL() 功能。没必要用它来做衣服 discount_percentage 就像你一样 IS NOT NULL 作为标准。另外,如果 quantity 指的是产品的数量,我认为你不应该返回1时 quantity 为空。
假设“dd”代表“直接折扣”,我不明白为什么你的记录有“dd”代码而没有 discount_percentage . 尽管如此,我认为下面的修改 CASE 声明将满足您的需要。

  1. CASE
  2. WHEN
  3. Product.discount_cd LIKE 'DD%' --Any code beginning with 'DD'
  4. AND discount_percentage IS NOT NULL --Must have discount percentage
  5. THEN (unitPrice * ISNULL(quantity,0)) - (unitPrice * ISNULL(quantity,0) * discount_percentage)
  6. WHEN
  7. Promotion_Type.discount_cd LIKE 'QB%' --Any code beginning with 'QB'
  8. AND discount_amount IS NOT NULL --Must have discount amount
  9. THEN unitPrice * ISNULL(quantity,0) - discount_amount
  10. ELSE 0 --No valid discount
  11. END AS reduce
展开查看全部
p8ekf7hl

p8ekf7hl2#

检查第一个条件,

  1. case when Product.discount_cd NOT LIKE '%DD' AND discount_percentange IS NOT NULL
  2. THEN (unitPrice*ISNULL(discount_percentange,1))*ISNULL(quantity,1)

单位折扣金额应从单价中扣除。

  1. case when Product.discount_cd NOT LIKE '%DD' AND discount_percentange IS NOT NULL
  2. THEN (unitPrice-(unitPrice*ISNULL(discount_percentange,1)))*ISNULL(quantity,1)

相关问题