Merging data in a single SQL table without a Cursor

后端 未结 4 1234
-上瘾入骨i
-上瘾入骨i 2021-01-31 19:51

I have a table with an ID column and another column with a number. One ID can have multiple numbers. For example

ID | Number
 1 |  25
 1 |  26
 1 |  30
 1 |  24
         


        
4条回答
  •  庸人自扰
    2021-01-31 20:51

    CREATE TABLE Table1
        ([ID] int, [Number] int)
    ;
    
    INSERT INTO Table1
        ([ID], [Number])
    VALUES
        (1, 25),
        (1, 26),
        (1, 30),
        (1, 24),
        (2, 4),
        (2, 8),
        (2, 5)
    ;
    
        select ID, 
               MIN(Number)
             ,(SELECT MIN(Number) 
                      FROM (SELECT TOP 2 Number from Table1 WHERE ID =
                      T1.Id ORDER BY Number DESC) as DT)
        from Table1 as T1
        GROUP BY ID
        UNION 
        SELECT ID, MAX(Number), MAX(Number)
        FROM Table1 as T1
        GROUP BY ID;
    

    Live Example

提交回复
热议问题