2015-08-23 80 views
0

我有一個SQL Server中的一個表中有一個巨大的數字範圍。我希望能夠爲特定範圍的值設置顏色。如果它在0到20%之間,它應該是紅色的,然後是21到40%,它應該是藍色的,等等。如何在SQL Server中爲特定範圍的值設置顏色?

我試過一些代碼,但它返回一些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

預先感謝您。

+0

您錯過了20-21,40-41等值之間的錯誤。使用之間創建間隙,交換到>和< – lad2025

回答

0

使用BETWEEN在值之間創建間隙。您需要使用比較運算符。

試試這個:

WITH cte([% APL Population],[% APL PopulationPercent]) 
AS 
(
    SELECT 
     [% APL Population] 
     ,[% APL PopulationPercent] = ([% APL Population]/NULLIF(Max([% APL Population]) OVER(), 0)) * 100 
    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 AND [% APL PopulationPercent] <= 100 THEN 'purple' 
      ELSE 'unknown' 
    END 
FROM cte 
+0

空值被替換爲「未知」,但我需要在一個範圍內的值,以便我可以根據範圍給它一個顏色。 – Musi

+0

APL人口也返回NULL嗎? – lad2025

+0

不,如果你看問題中的圖像,你會看到APL Poplulation的值。 – Musi

1

您不能在這種情況下使用between

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

問題是因爲20.5比20 grather和小於21歲。然後,對不符合條件case

+0

非常感謝你! – Musi

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 
相關問題