我需要一个新列,方法是从SQL Server的现有列中赋值.

我想要根据commission个金额得到commission2栏.

有客户可以包括1个或2个品牌和佣金金额.

Customerid CountCustomer Brand commission commission2
1000 1 B -28 0
1001 2 B 12 12
1001 2 F 252 252
1002 1 B 62 62
1003 1 B 5 5
1004 1 B -61 0
1005 1 F 0 0
1006 1 F 32 32
1007 1 F 0 0
1008 1 B -496 0
1009 1 F 1 1
1010 1 B 1 1
1011 1 B 0 0
1012 1 F -10 0
1013 1 B 82 82
1014 1 B 54 54
1015 1 B 18 18
1016 1 B 0 0
1017 2 B 0 0
1017 2 F -21 0
1018 1 B 0 0
1019 1 B 5 5
1020 1 B -3 0
1021 1 F -1 0
1022 1 B 95 95
1023 1 B -20 0
1024 1 B 0 0
1025 2 B -65 10
1025 2 F 10 10
1026 2 B 24 24
1026 2 F -7 24
1027 2 B 0 0
1027 2 F 0 0

以下是规则:

  • 如果是CountCustomer = 1,那就很容易了.如果是commission <= 0,则commission2是0,否则等于commission

  • 如果CountCustomer = 2(表示客户使用两个品牌),并且佣金金额之一为&gt;0,另一个为&lt;0,则两个commission2值都应为正数.如果这两个佣金数字都大于0,那么这些数字应该保持不变,为commission2.如果两个佣金都是&lt;0,那么两个佣金的佣金2都应该是0.您可以从上表的粗体行中更清楚地了解.

推荐答案

使用窗口功能查看每个客户的条目数以及最低和最高佣金:

select 
  customerid,
  count(*) over (partition by customerid) as countcustomer,
  brand,
  commission,
  case 
    when count(*) over (partition by customerid) = 1 then
      case when commission < 0 then 0 else commission end
    else
      case 
        when max(commission) (partition by customerid) <= 0 then
          0
        when min(commission) (partition by customerid) >  0 then
          commission
        else
          max(commission) (partition by customerid)
      end
  end as commission2
from mytable
order by customerid, brand;

或者,由于多行条件也适用于单行客户,只需:

select 
  customerid,
  count(*) over (partition by customerid) as countcustomer,
  brand,
  commission,
  case 
    when max(commission) (partition by customerid) <= 0 then
      0
    when min(commission) (partition by customerid) >  0 then
      commission
    else
      max(commission) (partition by customerid)
  end as commission2
from mytable
order by customerid, brand;

Sql相关问答推荐

Postgres trunc_date删除一个月

如何在幂函数中正确使用Power()和Exp()

使用Lead获取下一个不同的日期

更新其组的日期字段值小于最大日期减go 天数的记录

根据时间、状态和相关行在PostgreSQL中的存在来删除行

如何为缺少的类别添加行

将时间戳四舍五入到最近 10 分钟的查询

在 PostgreSQL 中,如何让多个判断约束引用相同的值数组?

如何为给定的股票数据集计算利润/亏损,确保先卖出先买入的股票

将varchar (7)列转换为datetime

标量子查询中的窗口函数不起作用

Postgres数据库维护:基于GROUP BY删除旧记录

带有数组输入参数的Snowflake UDF优化

如何通过CROSS APPLY获取多级嵌套JSON属性的值?

String_Split 多列

如何 Select 一列具有最小值而另一列具有给定值的记录?

我如何编写一个遍历数组数组并将所有值连接成一个字符串的 postgres 函数

连续几天购买的客户

SQL - 使用子查询返回多行的 LIKE 命令

聚合 Athena 中的列