2017-09-06 88 views
0

我有一個SQL Server表看起來像這樣一列price創建新列類價格:SQL服務器:根據價格列

10 
96 
64 
38 
32 
103 
74 
32 
67 
103 
55 
28 
30 
110 
79 
91 
16 
71 
36 
106 
89 
87 
59 
41 
56 
89 
68 
32 
80 
47 
45 
77 
64 
93 
17 
88 
13 
19 
83 
12 
76 
99 
104 
65 
83 
95 

現在我的目標是創建一個新列給出從1類別到10的每個值。

例如在我的列中的最大值爲110分鐘爲10最大 - 最小值= 100。然後,如果我想有10類我做十分之百= 10,因此這裏的範圍:

10-20 1 
21-30 2 
31-40 3 
41-50 4 
51-60 5 
61-70 6 
71-80 7 
81-90 8 
91-100 9 
101-110 10 

所需的輸出:

我的新列名爲cat應該是這樣的:

price  cat 
----------------- 
10   1 
96   9 
64   6 
38   3 
32   3 
103   10 
74   7 
32   3 
67   6 
103   10 
55   5 
28   2 
30   3 
110   10 
79   7 
91   9 
16   1 
71   7 
36   3 
106   10 
89   8 
87   8 
59   5 
41   4 
56   5 
89   8 
68   6 
32   3 
80   7 
47   4 
45   4 
77   7 
64   6 
93   9 
17   1 
88   8 
13   1 
19   1 
83   8 
12   1 
76   7 
99   9 
104   10 
65   6 
83   8 
95   9 

有T A方式用T-SQL執行此操作?對不起,如果這個問題可能太簡單了。我在網上搜索了很長時間。所以要麼這個問題不像我想象的那麼簡單。要麼我輸入了錯誤的關鍵字。

+0

所以範圍是在數據庫中,還是應該創建它作爲解決方案的一部分? –

+0

範圍不在數據庫中。我應該能夠找到一個靈活的解決方案。例如。對於給定的數據集,我應該可以選擇10個範圍,如果我想要更改爲4,我應該可以輕鬆完成。 – S12000

回答

2

是的,幾乎完全一樣,你描述的計算:

select price, 
     1 + (price - min_price) * 10/(max_price - min_price + 1) as decile 
from (select price, 
      min(price) over() as min_price, 
      max(price) over() as max_price 
     from t 
    ) t; 

1 +是因爲所需的值從1到10,而不是0到9

+0

什麼是新的列名稱 - 十分位數? – Eli

0

是的 - 一個case語句可以做到這一點。

select 
    price 
    ,case 
     when price between 10 and 20 then 1 
     when price between 21 and 30 then 2 
     when price between 31 and 40 then 3 
     when price between 41 and 50 then 4 
     when price between 51 and 60 then 5 
     when price between 61 and 70 then 6 
     when price between 71 and 80 then 7 
     when price between 81 and 90 then 8 
     when price between 91 and 100 then 9 
     when price between 101 and 110 then 10 
     else null 
    end as cat 
from [<enter your table name here>] 
+0

你好,非常感謝你的回答。但我的意思是我不打算強硬這樣的價值觀。例如,我希望能夠根據我擁有的數據調整範圍(有時候最大值可能不是110 ...),我也計劃選擇不同的範圍(不總是10)。 – S12000

+0

您的意思是硬編碼。你的邏輯是否總是在10的範圍內取值?含義,百分位數。 – Eli

+0

你的意思是硬編碼。是。你的邏輯是否總是在10的範圍內取值? NO – S12000