Warm tip: This article is reproduced from serverfault.com, please click

database-如何添加特定类别每月总销售额的条件

(database - How can I add condition for total sales per month for specific category)

发布于 2020-11-28 06:44:51

假设有一个如下表的结构

select Year, Month , customer, Category, Amount 
from claim

我想为每个月应用折扣,如表(绿色列)所示:

  • 如果JAN中品牌和非专利类别的“ Cus X”总销售额大于15000,则仅对2%的“品牌”类别应用折扣
  • 如果大于20000,则应用3%的折扣

对于其他月份和客户来说也是一样。

是否可以在SQL中使用子查询或某些可以帮助你的函数来做到这一点?

请指教

在此处输入图片说明

Questioner
Maram A-zaid
Viewed
0
Popeye 2020-11-28 15:35:27

你可以使用case .. when语句和解析函数,如下所示:

select Year, Month , customer, Category, Amount,
       Case when category = 'Brand'
            then
              Case when total_sales > 15000 then '2%'
                   When total_sales > 20000 then '3%'
              End
       End as disc,
       Case when category = 'Brand' 
            then
              Case when total_sales > 15000 then 2*amount/100
                   When total_sales > 20000 then 3*amount/100
              End
       End disc_amount
From
(select Year, Month , customer, Category, Amount,
        sum(case when category in ('Brand', 'Generic') then amount else 0 end)
          over (partition by year, month, customer) as total_sales
 from claim)