June 4, 2015 at 9:23 am
Hi I am trying to increment a column that I am creating in a select by 5's, example 5,10,20,25....first row starting at 5,
Something like
WITH CTE as
(
SELECT cast(5 as int) as myColumn from table
)
SELECT cte.myColumn + 5 from CTE
June 4, 2015 at 9:26 am
I think row_number is they way to go here; then you cna just multiply it by five.
WITH CTE as
(
SELECT row_number() over(order by MyPrimarykey) * 5 as myColumn from table
)
SELECT myColumn from CTE
Lowell
June 4, 2015 at 11:25 am
It might not relate to the question directly, but if the number will be stored, this could be an alternative.
CREATE TABLE #Increments(
id5 int IDENTITY(5,5),
somevalue varchar(128)
)
INSERT INTO #Increments(somevalue)
SELECT TOP 100 name
FROM sys.all_objects
SELECT *
FROM #Increments
ORDER BY id5
DROP TABLE #Increments
June 4, 2015 at 6:17 pm
I have a get numbers function that I use for exactly this sort of thing. It comes in handy often...
IF OBJECT_ID('dbo.GetNumsAB','IF') IS NOT NULL
DROP FUNCTION dbo.GetNumsAB;
GO
CREATE FUNCTION dbo.GetNumsAB(@low int, @high int, @gap int)
RETURNS TABLE WITH SCHEMABINDING AS RETURN
WITH
L1(N) AS (SELECT 1 FROM (VALUES (1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) t(N)), --10
L3(N) AS (SELECT 1 FROM L1 a, L1 b, L1 c), --1000
iTally AS (SELECT N = ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) FROM L3 a, L3 b) --1M
SELECT TOP (ABS((@high-@low)/ISNULL(NULLIF(@gap,0),1)+1)) -- prevent divide by 0 error is @gap=0
rn = N,
n1 = ((N-1)*@gap+@low)
FROM iTally
WHERE @high >= @low; -- ensure that @high >= @low
GO
SELECT
rn, -- ROW_NUMBER() is built in if you need it...
n1
FROM dbo.GetNumsAB(5,100,5);
-- Itzik Ben-Gan 2001
Viewing 4 posts - 1 through 3 (of 3 total)
You must be logged in to reply to this topic. Login to reply