SQL Server按GroupID排序随机但每个GroupID中的asc ID

时间:2015-01-21 03:29:31

标签: sql-server group-by sql-update sequential-number

我正在使用SQL Server 2012。

每次我按照以下规则执行SQL时,我想将序号设置为Num字段:

  • Grp命令随机化。
  • 要提升的身份字段。

有人可以为我解释一下吗?

表格

    +-----+-----+----+
    | Num | Grp | ID |
    +-----+-----+----+ 
    |   0 |   1 |  1 | 
    |   0 |   1 |  2 | 
    |   0 |   1 |  3 | 
    |   0 |   2 |  4 | 
    |   0 |   2 |  5 |
    |   0 |   2 |  6 | 
    |   0 |   2 |  7 | 
    |   0 |   3 |  8 | 
    |   0 |   3 |  9 | 
    |   0 |   4 | 10 | 
    |   0 |   4 | 11 | 
    |   0 |   4 | 12 | 
    |   0 |   4 | 13 | 
    |   0 |   4 | 14 | 
    +-----+-----+----+ 

预期输出

    +-----+-----+----+ 
    | Num | Grp | ID |
    +-----+-----+----+
    |   1 |   3 |  8 |
    |   2 |   3 |  9 |
    |   3 |   1 |  1 |
    |   4 |   1 |  2 |
    |   5 |   1 |  3 |
    |   6 |   4 | 10 |
    |   7 |   4 | 11 |
    |   8 |   4 | 12 |
    |   9 |   4 | 13 |
    |  10 |   4 | 14 |
    |  11 |   2 |  4 |
    |  12 |   2 |  5 |
    |  13 |   2 |  6 |
    |  14 |   2 |  7 |
    +-----+-----+----+

1 个答案:

答案 0 :(得分:1)

样本表

CREATE TABLE #TEMP(Num INT, Grp INT, ID INT)

   INSERT INTO #TEMP
    SELECT   0 ,   1 ,  1 
    UNION ALL
     SELECT    0 ,   1 ,  2 
     UNION ALL
    SELECT     0 ,   1 ,  3 
    UNION ALL
    SELECT     0 ,   2 ,  4
    UNION ALL
    SELECT     0 ,   2 ,  5
    UNION ALL
    SELECT     0 ,   2 ,  6 
    UNION ALL
    SELECT     0 ,   2 ,  7 
    UNION ALL
    SELECT     0 ,   3 ,  8
    UNION ALL
    SELECT     0 ,   3 ,  9 
    UNION ALL
    SELECT     0 ,   4 , 10
    UNION ALL
    SELECT     0 ,   4 , 11 
    UNION ALL
    SELECT     0 ,   4 , 12 
    UNION ALL
    SELECT     0 ,   4 , 13
    UNION ALL
    SELECT     0 ,   4 , 14 

<强> QUERY

;WITH CTE2 AS
(
    -- Now GRP will be ordered in random order using NEWID()
    SELECT ROW_NUMBER() OVER(ORDER BY NEWID()) RNO,GRP 
    FROM 
    (
        -- Select unique GRP's
        SELECT DISTINCT GRP
        FROM #TEMP
    )TAB

)
SELECT ROW_NUMBER() OVER(ORDER BY rno,ID ASC) NUM,
C2.GRP,C1.ID
FROM CTE2 C2
JOIN #TEMP C1 ON C2.GRP=C1.GRP
order by rno,ID ASC 

<强>更新

以下是使用新行号更新表格中的NUM字段的查询。

;WITH CTE2 AS
(
    SELECT ROW_NUMBER() OVER(ORDER BY NEWID()) RNO,GRP 
    FROM 
    (
        SELECT DISTINCT GRP
        FROM #TEMP
    )TAB

)
UPDATE #TEMP SET NUM = TAB.NUM
FROM
(
    SELECT ROW_NUMBER() OVER(ORDER BY rno,ID ASC) NUM,
    C2.GRP,C1.ID
    FROM CTE2 C2
    JOIN #TEMP C1 ON C2.GRP=C1.GRP
)TAB
WHERE #TEMP.GRP=TAB.GRP AND #TEMP.ID=TAB.ID


SELECT * FROM #TEMP
order by NUM,ID ASC