Sql group rows with same value, and put that value into header?

前端 未结 5 1943
梦毁少年i
梦毁少年i 2020-12-11 04:50

I want to group rows with SQL, my result set is following

name  size  date
data1  123  12/03/2009
data1 &nb

5条回答
  •  时光说笑
    2020-12-11 05:17

    There might be something like:

    select name, size, date from
    (
    -- select only distinct rows, and empty values for size and date (header rows)
    select ROWNUM rown, name, '', ''
    from T
    group by name
    order by name
    
    union all
    
    -- select all data (non-header records)
    select ROWNUM+1 rown, name, size, date 
    from T 
    order by name
    )
    order by name, rown
    

    Explanation: First select from the union selects the records for the group header. It sorts the results by name. The row number gives the order. Second select from the union selects all the records for the group header. It sorts the results by name, and the row number gives the order. The union put all the information together. ROWNUM+1 for the second select ensures that records for the header (from the first select) are ordered before the detailed records.

    Now... what you need to do and I don't recover so much SQL to know how to do it... is to put '' for name when size or date are '', in the main select (with a case/swich operation). Some help is needed here :).

    Just as an observation, in the provided SQL, ROWNUM is a special column that provides the row number for a select (see Oracle for example).

    The query is displayed just as principle, I am not 100% sure it works.

    Update: ... thats a solution sketch. But I still believe this is a formatting problem, and not an SQL problem.

提交回复
热议问题