十进制值的不同范围(间隔)的不同计算

时间:2012-09-18 04:04:04

标签: sql tsql

十进制类型字段需要拆分为范围(间隔),计算方式不同然后总结。

此问题涉及字段值,而不是行。 因此对于表中每一行的某个字段(fieldX):

FieldX <  0.013           <----remain just FieldX
FieldX >= 0.013 to 0.026  <----be multiplied with 50%.
FieldX >  0.026           <----be omitted.

编辑评论:以下示例显示了闭合范围[0.013, 0.026]中表达式为的值:

  • 0.013 + (FieldX - 0.013) * 0.5

然后需要将这些范围(间隔)或部分相加。

示例案例:

FieldX     Result
-0.12      -0.12
-0.05      -0.05
+0.05      +0.05                                 — mismatch with specification
+0.011     +0.011
+0.014     +0.0135 = (0.013 + (0.014-0.013)*50%)
+0.021     +0.017  = (0.013 + (0.021-0.013)*50%)
+0.026     +0.0195 = (0.013 + (0.026-0.013)*50%)
+0.031     +0.0195 = (0.013 + (0.026-0.013)*50%) — mismatch with specification

我将向解决它的天才颁发诺贝尔奖!

2 个答案:

答案 0 :(得分:0)

您应该可以使用CASE Statement

执行此操作
SELECT  *,
        CASE 
            WHEN FieldX < 0.013
                THEN FieldX
            WHEN FieldX >= 0.013 and FieldX < 0.026 
                THEN 0.013 + (FieldX - 0.013 ) * .5
            ... and so on
        END
FROM    [Table]

答案 1 :(得分:0)

SELECT SUM(CASE
           WHEN FieldX <  0.013 THEN FieldX
           WHEN FieldX <= 0.026 THEN 0.013 + 0.5 * (FieldX - 0.013)
           ELSE                     NULL
           END)
  FROM YourTable

聚合忽略NULL,这相当于忽略它。请注意,对于SUM(),您可以使用0.0代替NULL,但不能使用COUNT或AVG。忽略行的另一种方法是使用WHERE子句过滤掉它们,当然:

SELECT SUM(CASE
           WHEN FieldX <  0.013 THEN FieldX
           WHEN FieldX <= 0.026 THEN 0.013 + 0.5 * (FieldX - 0.013)
           END)
  FROM YourTable
 WHERE FieldX <= 0.026