SQL Server:DENSE_RANK()

时间:2011-09-19 20:30:05

标签: sql-server sequence dense-rank

我有一张桌子A: (ID int,batch int,new_batch int)

已填充ID和批次:

ID  Batch New_Batch
1   01    NULL
2   01    NULL
3   02    NULL
4   02    NULL
5   02    NULL
6   03    NULL
7   04    NULL
8   05    NULL

现在我想根据以下select语句填充New_batch。

(select batch from tableA where id in (3,8))
  1. 现在对于这个select语句,我们得到batch = 02和batch = 5。现在我想分配new_batch,以便首先排序select语句的结果(batch02然后批处理05),剩余数据应按批次NOT的递增顺序排序。 (批次1,3,4) 结果应该是:

  2.       ID Batch New_Batch
           1   01    03
           2   01    03
           3   02    01
           4   02    01
           5   02    01
           6   03    04
           7   04    05
           8   05    02
    

    感谢。 PS:DENSE_RANK()可以使用,请不要硬编码!!

2 个答案:

答案 0 :(得分:4)

/*Please provide DDL like the below for future questions*/
DECLARE @tableA TABLE
(
ID INT PRIMARY KEY,
Batch INT,
New_Batch INT NULL
)

INSERT INTO @tableA(ID,Batch)
SELECT 1,1 UNION ALL
SELECT 2,1 UNION ALL   
SELECT 3,2 UNION ALL   
SELECT 4,2 UNION ALL   
SELECT 5,2 UNION ALL   
SELECT 6,3 UNION ALL   
SELECT 7,4 UNION ALL   
SELECT 8,5   

/*Answer*/
;WITH T
     AS (SELECT *,
                DENSE_RANK() OVER (ORDER BY 
                      CASE
                        WHEN Batch IN (SELECT Batch
                                       FROM   @tableA
                                       WHERE  ID IN ( 3, 8 )) 
                         THEN 0 
                         ELSE 1 END, Batch) AS NB
         FROM   @tableA)
UPDATE T
SET    New_Batch = NB

SELECT *
FROM   @tableA  

答案 1 :(得分:2)

declare @T table
(
  ID int,
  Batch char(2),
  New_Batch char(2)
)

insert into @T values
(1,   '01',    NULL),
(2,   '01',    NULL),
(3,   '02',    NULL),
(4,   '02',    NULL),
(5,   '02',    NULL),
(6,   '03',    NULL),
(7,   '04',    NULL),
(8,   '05',    NULL)

;with C as
(
  select T1.New_Batch,
         dense_rank() over(order by -T2.ID desc, T1.Batch) as rn
  from @T as T1
    left outer join (select Batch, ID 
                     from @T
                     where ID in (3, 8)) as T2
      on T1.Batch = T2.Batch 
)
update C 
set New_Batch = right(100+rn, 2)


select *
from @T
order by ID

在此尝试:http://data.stackexchange.com/stackoverflow/q/113031/