我想要一个按照规则的 SQL 计算列

发布于 2024-08-09 07:35:17 字数 621 浏览 5 评论 0原文

我希望能够在一列中存储十进制值,并在另一列中存储表示选项的 int (将解释):

  1. 应该是基数 -%
  2. 应该是基数 -absolute
  3. 应该是基数 +%
  4. 应该是基数+绝对
  5. 1& 2是折扣
  6. 3& 4是附加费
  7. 1& 3 按百分比减少/增加金额(即金额*金额/值)。
  8. 2& 4 减少/增加绝对金额(即金额+/-值)。

意思是我有一个包含 3 列的表:

  • BasePrice MoneyAdditionalPricedecimalOptiontinyint
  • 根据选项,

ComputedColumn

  • (十进制?)

假设我们有一行 BasePrice 为 100,AdditionalPrice 为 0.20

计算的 col 应生成以下值:

  • 80
  • 99.80
  • 120
  • 100.20

我说清楚了吗? 我有什么办法可以实现这个目标吗?

I want to be able to store a decimal value in one column, and in the other column to store an int that represents the option (will explain):

  1. should be base -%
  2. should be base -absolute
  3. should be base +%
  4. should be base +absolute
  5. 1 & 2 is a discount
  6. 3 & 4 is an upcharge
  7. 1 & 3 reduces/raises the amount by percentage (i.e. amount * amount/value).
  8. 2 & 4 reduces/raises the amount absolutely (i.e. amount +/- value).

Meaning I have a table of 3 columns:

  • BasePrice money
  • AdditionalPrice decimal
  • Option tinyint

and

  • ComputedColumn (decimal?)

let's say we have a row that it's BasePrice is 100 and the AdditionalPrice is 0.20

According to the option the computed col should generate the following value:

  • 80
  • 99.80
  • 120
  • 100.20

Am I clear?
Is there any way I can achieve this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

沫雨熙 2024-08-16 07:35:17

我也会将计算列保留为金钱。

在内部,由于数据类型优先级,这将转换为十进制

CREATE TABLE (
...,
ComputedColumn AS CAST (
    CASE Option
        WHEN 1 THEN BasePrice * (1 - AdditionalPrice)
        WHEN 2 THEN BasePrice - AdditionalPrice
        WHEN 3 THEN BasePrice * (1 + AdditionalPrice)
        WHEN 4 THEN BasePrice + AdditionalPrice
    END AS money)
)

I'd keep the computed column as money too.

Internally, this will cast to decimal because of Data Type Precedence

CREATE TABLE (
...,
ComputedColumn AS CAST (
    CASE Option
        WHEN 1 THEN BasePrice * (1 - AdditionalPrice)
        WHEN 2 THEN BasePrice - AdditionalPrice
        WHEN 3 THEN BasePrice * (1 + AdditionalPrice)
        WHEN 4 THEN BasePrice + AdditionalPrice
    END AS money)
)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文