如何在SQL Server中为特定范围的值设置颜色?

时间:2015-08-23 18:06:20

标签: sql sql-server

我在SQL Server中有一个包含大量数字的表。我希望能够为特定范围的值设置颜色。如果它介于0到20%之间,它应该是红色,然后是21到40%,应该是蓝色,依此类推。

我尝试了一些代码,但它返回了一些NULL值,我不明白为什么。我该如何解决这个问题?

WITH cte  as 
(
   SELECT 
       [% APL Population],
       ([% APL Population] / NULLIF(Max([% APL Population]) OVER(), 0) ) * 100 AS [% APL PopulationPercent] 
   FROM   
       dbo.Indicators) 
SELECT 
    [% APL Population],
    [% APL Populationcolor] = 
       CASE 
          WHEN [% APL PopulationPercent] BETWEEN 0 AND 20 THEN 'red' 
          WHEN [% APL PopulationPercent] BETWEEN 21 AND 40 THEN 'blue' 
          WHEN [% APL PopulationPercent] BETWEEN 41 AND 60 THEN 'green' 
          WHEN [% APL PopulationPercent] BETWEEN 61 AND 100 THEN 'purple' 
       END 
FROM cte

enter image description here

提前谢谢。

3 个答案:

答案 0 :(得分:1)

在这种情况下,您无法使用between

WHEN [% APL PopulationPercent] < 20 THEN 'red' 
WHEN [% APL PopulationPercent] >= 20 AND [% APL PopulationPercent ] <40 THEN 'blue' 
...

问题是因为20.5比20小于21且小于21.然后不匹配任何case条件。

答案 1 :(得分:0)

使用BETWEEN可以在值之间创建差距。您需要使用比较运算符。

试试这个:

{
  "_id" : ObjectId("55c455c2fc07853b78c4b6b9"),     
  "data": {
    "0": {
      "data": [
      {
        val1: "abc",
        val2: "def"
      },
      {
        val1: "abc",
        val2: "def"
      }
      ]
    }
  }
}

答案 2 :(得分:0)

您的CASE表达式并未考虑范围之间的小数值。尝试包含开始和独占结束范围,如下例所示,修改所需的存储桶。

WITH    cte
          AS ( SELECT   [% APL Population]
                      , ( [% APL Population]
                          / NULLIF(MAX([% APL Population]) OVER ( ), 0) )
                        * 100 AS [% APL PopulationPercent]
               FROM     dbo.Indicators
             )
    SELECT  [% APL Population]
          , [% APL Populationcolor] = CASE WHEN [% APL PopulationPercent] >= 0 AND [% APL PopulationPercent] < 20
                                           THEN 'red'
                                           WHEN [% APL PopulationPercent] >= 20 AND [% APL PopulationPercent] < 40
                                           THEN 'blue'
                                           WHEN [% APL PopulationPercent] >= 40 AND [% APL PopulationPercent] < 60
                                           THEN 'green'
                                           WHEN [% APL PopulationPercent] >= 60                                             THEN 'purple'
                                      END
    FROM    cte