我在SQL Server 2008数据库中有一个表,我想在1到10的范围内安排一个数字列。
这是一个示例,其中列(Scale
)是我想用SQL
Name Count (Scale)
----------------------
A 19 2
B 1 1
C 25 3
D 100 10
E 29 3
F 60 7
在上面的例子中,最小和最大计数是1和100(这可能每天都不同)。
我想得到每个记录所属的数字。
1 = 0-9
2 = 10-19
3 = 20-29 and so on...
它必须是动态的,因为这些数据每天都在变化,所以我不能使用WHERE
子句和静态数字,如下所示:WHEN Count Between 0 and 10...
答案 0 :(得分:1)
您可以将Scale
列PERSISTED COMPUTED
列设为:
alter table test drop column Scale
ALTER TABLE test ADD
Scale AS (case when Count between 0 and 9 then 1
when Count between 10 and 19 then 2
when Count between 20 and 29 then 3
when Count between 30 and 39 then 4
when Count between 40 and 49 then 5
when Count between 50 and 59 then 6
when Count between 60 and 69 then 7
when Count between 70 and 79 then 8
when Count between 80 and 89 then 9
when Count between 90 and 100 then 10
end
)PERSISTED
GO
答案 1 :(得分:1)
尝试这一点,虽然从技术上讲,值100不会落在90-99的范围内,因此应该被归类为11,因此为什么值60的比例为6而不是7:
MS SQL Server 2008架构设置:
查询1 :
create table #scale
(
Name Varchar(10),
[Count] INT
)
INSERT INTO #scale
VALUES
('A', 19),
('B', 1),
('C', 25),
('D', 100),
('E', 29),
('F', 60)
SELECT name, [COUNT],
CEILING([COUNT] * 10.0 / (SELECT MAX([Count]) - MIN([Count]) + 1 FROM #Scale)) AS [Scale]
FROM #scale
<强> Results 强>:
| NAME | COUNT | SCALE |
|------|-------|-------|
| A | 19 | 2 |
| B | 1 | 1 |
| C | 25 | 3 |
| D | 100 | 10 |
| E | 29 | 3 |
| F | 60 | 6 |
这可以让你得到答案,其中60变为7,因此100是11:
SELECT name, [COUNT],
CEILING([COUNT] * 10.0 / (SELECT MAX([Count]) - MIN([Count]) FROM #Scale)) AS [Scale]
FROM #scale
答案 2 :(得分:1)
select ntile(10) over (order by [count])
答案 3 :(得分:0)
WITH MinMax(Min, Max) AS (SELECT MIN(Count), MAX(Count) FROM Table1)
SELECT Name, Count, 1 + 9 * (Count - Min) / (Max - Min) AS Scale
FROM Table1, MinMax