【问题标题】:PostgreSQL, Change values after a limit is reachedPostgreSQL,达到限制后更改值
【发布时间】:2017-09-22 17:55:58
【问题描述】:

我有以下表格

折扣订单

id | employee |
---|----------|
 1 |1         |
 2 |2         |
 3 |1         |
 4 |3         |
 5 |3         |
 6 |1         |
 7 |1         |
 8 |1         |
 9 |1         |

我在其他地方有员工工资。

我想做的是以下。

如果员工存在于折扣订单表中,请执行以下操作:

->“discounts orders 表”上的 1 行将工资值的 30% 打折,并在“表 X”上插入 1 行,其中包含employee_id 的金额和折扣值。

->“discounts orders 表”上的 2 行从工资值中扣除 30%,并在“表 X”上插入 2 行,其中包含employee_id 的金额和折扣值。

-> “discounts orders 表”上的 3 行将工资值的 30% 打折,并在“表 X”上插入 3 行,其中包含employee_id 的金额和折扣值。

->“折扣订单表”上的 4 行从工资值中扣除 30%,并在“表 X”上插入 3 行,其中包含employee_id 的金额和折扣值(3 次乘以 30% 为工资的 90% ) 插入的第 4 行应为 10%(达到工资的 100%)

-> “折扣订单表”中的 >4 行执行上述情况的流程并忽略其余部分。 (因为你不能折扣超过工资的 100%)

如果员工 #1 赚了 1000 美元,并且在“折扣订单表”上有 10 行 X 表应该是这样的

id | employee | discount_value | discounts_orders_id
---|----------|----------------|--------------------
1  | 1        | 300            | 1
2  | 1        | 300            | 3
3  | 1        | 300            | 6
4  | 1        | 100            | 7

编辑:

我找到了一个临时解决方案。

insert into "table x" ....
select (employee_salary * 0.30) from employee
inner join discounts_orders ....
limit 4

我用 (salary * 0.30) 插入 4 行,然后用 (salary * 0.10) 更新 1 行

【问题讨论】:

  • 请告诉我们您到目前为止尝试过的代码!
  • 嗨,Alex,我更新了帖子,你可以看到一个临时解决方案,我敢打赌会有更好的选择。

标签: sql postgresql limit


【解决方案1】:

我会尝试使用子查询来计算条目的数量,然后使用 CASE WHEN 来决定因子,如下所示:

insert into "table x" ....
select (employee_salary * 
  (CASE WHEN (SELECT COUNT(*) FROM discounts_orders as dior
             WHERE dior.employee=employee.id 
                  AND dior.id<=discounts_orders.id) < 4 
       THEN 0.30
       ELSE 0.10
       END)) from employee
inner join discounts_orders ....
limit 4

【讨论】:

    猜你喜欢
    • 2021-10-23
    • 1970-01-01
    • 2010-11-09
    • 1970-01-01
    • 1970-01-01
    • 2021-12-17
    • 2010-12-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多