使用Rank()函数

时间:2016-06-13 20:54:30

标签: sql sql-server

我有一张包含现有数据的表格。对于此表的第一列中的每个唯一值,我们有一个列应按顺序排列,但此表已失序。我想运行一个SQL语句,将第二列重新排列。我能用这个SQL看到我想要的结果:

select FORMULA_ID, ATTRIB_CODE, ATTRIB_VAL, ATTRIB_ORDER,
rank() over (partition by formula_id order by attrib_code, attrib_val) AS WANT_THIS
from ATTRIB

哪个收益率:

 FORMULA_ID  ATTRIB_CODE          ATTRIB_VAL       ATTRIB_ORDER WANT_THIS
 ----------- -------------------- ---------------- ------------ ---------
 2791        C_BRAND              ROMAN HOLIDAY    3            1
 2791        C_ENDUSE             DINNER           4            2
 2791        C_ENDUSE             SNACK            6            3
 2791        C_ENDUSER            10-17            7            4
 2791        C_PRODTYPE           SALAD            13           5
 2791        C_RELIG              ANY              14           6
 2821        C_ALLERGEN           PEANUT           1            1
 2821        C_ALLERGEN           SOY              2            2
 2821        C_BRAND              ROMAN HOLIDAY    1            3
 2821        C_ENDUSE             DINNER           1            4

如您所见,WANT_THIS列对行进行排序,并在到达新的FORMULA_ID时重置为1。但我不知道如何将其转换为UPDATE语句,该语句实际上将WANT_THIS中的值放入ATTRIB_ORDER列中。有没有办法将上面的SQL转换为UPDATE语句?

1 个答案:

答案 0 :(得分:11)

这是一种方式:

WITH CTE AS
(
    SELECT  FORMULA_ID, 
            ATTRIB_CODE, 
            ATTRIB_VAL, 
            ATTRIB_ORDER,
            RANK() OVER (PARTITION BY formula_id 
                         ORDER BY attrib_code, attrib_val) AS WANT_THIS
    FROM ATTRIB
)
UPDATE CTE
SET ATTRIB_ORDER = WANT_THIS;