0
select MAX (cast (id as numeric)) from table --whatever value it may return

select 
(row_number ()  over (order by id)) as Number from table  --will start at 1

How do I combine the two so whatever value the first query returns, I can use that value and auto increment from there, somehow combining the two (tried nesting them, but unsuccessful) or do I need to...

  1. Declare a variable
  2. get my max id value
  3. make my variable equal to that
  4. then place that value/variable in my second statement?

Like...

select 
(row_number ()  over (order by id) + (declared_max_value)) as Number from table
4

4 回答 4

2

Try this:

WITH CTE as
(SELECT max(Field) FROM Table)
    SELECT WhatYouWant, cte.m FROM Table2
    INNER JOIN CTE ON 0=0

or this:

SELECT *, t.maxField FROM Table1 OUTER APPLY (SELECT max(Field) as maxField FROM Table2) t
于 2013-11-14T21:22:29.900 回答
0
declare @maxValue int
select @maxValue = select max(cast (id as integer)) from table

declare @uaerystring varchar(max)
select @queryString = 
'(row_number ()  over (order by id) + '
+ @maxValue +
')as Number from table'
Execute(@queryString)
于 2013-11-14T21:23:00.837 回答
0

Try this:

SELECT
    Seed.ID + ROW_NUMBER() OVER (order by T.ID) as Number,
    T.ID
FROM
    T CROSS JOIN
    (SELECT MAX(ID) AS ID FROM T) AS Seed

Working sample: http://www.sqlfiddle.com/#!3/a14ad/3

于 2013-11-14T21:24:44.997 回答
0
DECLARE @T Table (ID int , Value Varchar(20))
INSERT INTO @T (ID, Value)
VALUES (50, 'Value1'), (500, 'Value1'), (100, 'Value1'), (50, 'Value2'), (100, 'Value2'),(500, 'Value2')

;with CTE (Value, ID, rn)
AS
(
SELECT Value, MAX(ID), rn = ROW_NUMBER() OVER (ORDER BY Value ASC)
FROM 
@T
GROUP BY Value
)
SELECT * FROM CTE
于 2013-11-14T21:25:11.030 回答