SQL Server:根据价格列创建新的列类别价格

时间:2017-09-06 19:33:53

标签: sql sql-server range categories

我有一个列为price的SQL Server表,如下所示:

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,min为10. Max-min = 100.然后,如果我想要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-SQL执行此操作?对不起,如果这个问题太容易了。我在网上搜索了很长时间。所以要么问题不是我想象的那么简单。我输错了关键字。

2 个答案:

答案 0 :(得分: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.

答案 1 :(得分:0)

是的 - 案例陈述可以做到这一点。

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>]