对不起,我还是相当新的。我需要创建一个包含两列的SQL表:PrimaryNumber,ThousandRange
PrimaryNumber应该填充1到20,000之间的整数。 ThousandRange应填充PrimaryNumber各自的范围。
例如:
PrimaryNumber ThousandRange
1000 1000-1999
1001 1000-1999
1002 1000-1999
1003 1000-1999
... ...
2000 2000-2999
2001 2000-2999
2002 2000-2999
2003 2000-2999
等等。
答案 0 :(得分:1)
一种方法是相当复杂的case
表达式。一个更有趣的方法是使用字符串和算术:
select (floor(primarynumber / 1000)*1000 || '-' ||
(floor(primarynumber / 1000)*1000 + 999)
) as thousandrange
这使用ANSI标准语法。这种或类似的东西应该适用于大多数数据库。例如,Here是一个SQL小提琴。
编辑:
您也想创建表格。而SQL Server有点棘手。这是一种方法:
with n as (
select 1000 as n union all
select n + 1
from n
where n < 20000
)
select n as primarynumber,
replace(replace('[1]-[2]', '[1]', floor(n / 1000)*1000), '[2]', floor(n / 1000)*1000 + 999) as thousandrange
from n
option (maxrecursion 0);
Here是另一个示范。
答案 1 :(得分:1)
试试这个......
DECLARE @startnum INT=1000
DECLARE @endnum INT=20000
;WITH cte (primarynumber, thousandrange)
AS (SELECT @startnum,
@startnum
UNION ALL
SELECT primarynumber + 1,
( primarynumber + 1 ) - ( ( primarynumber + 1 ) % 1000 )
FROM cte
WHERE primarynumber < @endnum)
SELECT primarynumber,
Cast(thousandrange AS NVARCHAR(max)) + '-' + Cast(thousandrange+999 AS NVARCHAR(max)) AS thousandrange
FROM cte
OPTION (maxrecursion 20000)
...输出
+---------------+---------------+
| primarynumber | thousandrange |
+---------------+---------------+
| 1000 | 1000-1999 |
| 1001 | 1000-1999 |
| 1002 | 1000-1999 |
| --- | |
| 2783 | 2000-2999 |
| 2784 | 2000-2999 |
| 2785 | 2000-2999 |
| --- | |
| 7259 | 7000-7999 |
| 7260 | 7000-7999 |
| 7261 | 7000-7999 |
| --- | |
| 13737 | 13000-13999 |
| 13738 | 13000-13999 |
| 13739 | 13000-13999 |
| --- | |
| 17762 | 17000-17999 |
| 17763 | 17000-17999 |
| 17764 | 17000-17999 |
| --- | |
| 19998 | 19000-19999 |
| 19999 | 19000-19999 |
| 20000 | 20000-20999 |
+---------------+---------------+
答案 2 :(得分:0)
你只是这样做了一次所以它真的不需要是一个基于集合的&#34;&#34;查询。一个简单的循环将完美地运作。
create table N (PrimaryNumber int not null, ThousandRange varchar(12) not null);
declare @n int = 1;
while @n <= 20000
begin
insert into N (PrimaryNumber, ThousandRange) values
(@n, cast(@n / 1000 * 1000 as varchar(8)) + '-' +
cast(@n / 1000 * 1000 + 999 as varchar(8));
set @n = @n + 1;
end
commit;
在SQL Server中,它使用标准整数除法。